Justin John
Justin John

Reputation: 9616

Cake php validation rule 'isUnique' gives error on edit

The cake php validation 'isUnique' gives error on edit

 var $validate = array(
    'name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
        ),
       'isUnique' => array (

           'rule' => 'isUnique',

           'message' => 'This person name already exists.'
       )

)
);

Here when add a new person with existing name gives an error This person name already exists that is fine. But on edit of already existing person also gives the same isUnique error.

How I can sort it out ?

Upvotes: 2

Views: 3569

Answers (1)

tigrang
tigrang

Reputation: 6767

Try:

'isUnique' => array (

           'rule' => 'isUnique',

           'message' => 'This person name already exists.',

           'on' => 'create',
 )

From the book:

If a rule has defined ‘on’ => ‘create’, the rule will only be enforced during the creation of a new record. Likewise, if it is defined as ‘on’ => ‘update’, it will only be enforced during the updating of a record.

If, however, they are allowed to change the name, and you still need uniqueness from other records, you may need a custom unique validation which would check that if it is identical to the record of the id I'm editing allow that, otherwise fail.

Edit: Do NOT use the following - cakes built-in isUnique validation handles it already

Note - untested code (its late, I will test in the morning) but it will give you the idea

Add the following to the model and change 'rule' => 'isUnique', to 'rule' => 'isUniqueName' and remove 'on' => 'create'

public function isUniqueName($fields) {
        $conditions = array($this->alias . '.name' => $this->data[$this->alias]['name']);
        if (isset($this->data[$this->alias][$this->primaryKey])) {
            $conditions[$this->alias . '.' . $this->primaryKey . ' <>'] = $this->data[$this->alias][$this->primaryKey];
        }
        return $this->find('count', compact('conditions')) == 0;
}

Upvotes: 10

Related Questions