Bancha/Bancha — Issue #22: using $this->find() in a custom validation rule in cakePHP breaks model->save() when associations exist
Author: Aryantes
Created: 2012-01-05 16:13:57+00:00
State: open

When defining a CakeModel, you can create custom validation rules with custom functions.

If you define a custom rule, that uses $this->find(), the banchaBehavior breaks somewhere in beforeValidate(). ONLY IF you have associations in the model. Any association, hasMany, belongsTo, hasAndBelongsToMany, etc. This works properly accessing Cake directly, not using ExtJS.

It will attempt to use the wrong model to validate to buildFieldList() and then it will save a new record in the database with empty fields.

An example of the validation rules can be found here.
http://book.cakephp.org/2.0/en/models/data-validation.html

```ruby
class User extends AppModel {
public $name = 'User';

public $validate = array(
'promotion_code' => array(
'rule' => array('limitDuplicates', 25),
'message' => 'This code has been used too many times.'
)
);

function limitDuplicates($check, $limit) {
// $check will have value: array('promomotion_code' => 'some-value')
// $limit will have value: 25
$existing_promo_count = $this->find('count', array(
'conditions' => $check,
'recursive' => -1
));
return $existing_promo_count < $limit;
}
}
```