How to debug variable in function inside cakephp model

I am using Cakephp 2.3. In my model, I have a function to check for duplicates. I want to check the number of duplicates and report it to the user. However, the variable I set in the function seems to be not available to me in the view.

Model:

class Student extends AppModel {

public $validate = array(
'promotion_code' => array(
'rule' => array('limitDuplicates', 2),
'message' =>  "there are x duplicates" )
);

public function limitDuplicates($check, $limit) {
$existing_promo_count = $this->find('count', array(
'conditions' => $check,
'recursive' => -1
));
$this->set('results', $existing_promo_count);
return $existing_promo_count < $limit;
}
}

In the view

debug("duplicate count is ". $results);

results in

Notice (8): Undefined variable: results 

Please advice how to display a variable I set in a function in the model to be available to the error message in the View.

Thanks.

Hi, are there any cake php gurus out here? Please help!!! Thanks.

Hi vinai,

I’m no CakePHP guru I’m afraid (so apologies in advance if the code doesn’t work as-is), but I think you might be able to achieve what you want with the afterFind method:


public function afterFind($results, $primary = false) {
    foreach ($results as $key => $val) {
        if (isset($val['Student']['promotion_code'])) {
            $results[$key]['Student']['promotion_code_count'] = $this->limitDuplicates(
                array( 'promotion_code' => $val['Student']['promotion_code'] ), 2
            );
        }
    }
    return $results;
}

It looks like the downside to this method though is that your code will be executing an extra DB query for each model that you load, which might not be ideal if you’re loading a large set of Students.