0

I am trying to catch a certain findBy call (with afterFind) where:

if $results is empty (or the value you are trying to find is nonexistent), but the parameter value is found on another table, then it will modify $results to be valid

Some controller action got this:

$this->User->findByUsername("Bingo"); // yes, username Bingo doesnt exist on users table

User model:

function afterFind($results, $primary){
    if(empty($results)) {
        if(in_array($findbyparameter, array("Bingo", "Bingo1", "Bingo2"))) {
            // modify $results
        }
    }
}

The problem is, how do I get $findbyparameter?

Thanks! All help will be appreciated!

tereško
  • 58,060
  • 25
  • 98
  • 150
yowmamasita
  • 4,810
  • 3
  • 17
  • 17

2 Answers2

0

I am not using these convenience methods, but you can pass the variable as Model property like this:

//where you search 
$this->User->searchPhrase = "Bingo";
findByUsername($this->User->searchPhrase);

//Model
function afterFind($results, $primary){
    if(empty($results)) {
        if(in_array($this->searchPhrase, array("Bingo", "Bingo1", "Bingo2"))) {
            // modify $results
        }
    }
}

It's not the prettiest method, but I guess it would work. Try to print_r($this) in afterFind method and see if you can spot somewhere the phrase which you search. I believe it's passed in the condition's array.

Nik Chankov
  • 6,049
  • 1
  • 20
  • 30
  • Thanks for this. I'll be using this one instead. tried var_dump($this) on afterFind and found out that read() passes the params but not find (and findBy in effect) – yowmamasita Sep 23 '12 at 23:07
0

Perhaps a custom find type is what you're looking for. Custom find types have two states: before and after.

In the before you would setup your condition, and in the after you would check your data and modify if necessary. In both states you will have access to the query options.

Setting up custom finds is slightly different in 1.x and 2.x (you haven't mentioned which version you're using), so you can look up the specifics in the book.

In short, you would add add your the find type into the $findMethods property of the model and then add the corresponding method name to your model. Say you call your custom find type 'byUsername'

protected function _findByUsername($state, $query, $results = array()) {
    if ($state === 'before') {
        // add your condition to the query, 
        return $query;
    } elseif ($state === 'after') {
        // modify $results if you need to
        return $results;
    }
}

And you would call it via $this->User->find('byUsername', array('username' => $username));

In $query you would have the key 'username' which you can add to the conditions key of $query. In both states, you would have access to $query['username'].

tigrang
  • 6,767
  • 1
  • 20
  • 22