1
votes

I'm using CakePHP 2.0 and I have a model that I use validation on it like this:

 var $validate = array(
    'title' => array(
        'unique_rule'=>array(
            'rule' => 'isUnique',
            'on' => 'create',
            'message' => 'This title has already been taken.'
        ),
        'required_rule'=>array(
            'required' => true,
            'allowEmpty' => false,
            'message' => 'The title field is required.'
        )
    )
 );

, and in the controller I have an edit action and I use $model->save() to save date from $this->request->data, but it fails the isUnique validation rule, although it is not a new record insertion. Is there any way to specify that it is an existing record, not a new one ?

2
btw: your order is wrong and you should be using last=>true. there is no need in calling the DB for a unique check if there wasnt any input in the first place - mark

2 Answers

3
votes

If I got the question right you have to set the model's ID before calling $model->save(); so cakephp knows it's an update.

See http://book.cakephp.org/2.0/en/models/saving-your-data.html:

"Creating or updating is controlled by the model’s id field. If $Model->id is set, the record with this primary key is updated. Otherwise a new record is created:"

<?php
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);

// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
0
votes

your validation array is wrong you haven't set a rule for 'required_rule' wich might trigger the isUnique error message.

var $validate = array(
'title' => array(
    'unique_rule'=>array(
        'rule' => 'isUnique',
        'on' => 'create',
        'message' => 'This title has already been taken.',
        'last' => true
    ),
    'required_rule'=>array(
       'rule' => array('notEmpty'),             
        'message' => 'The title field is required.'
    )
)
);

Also remember that using required=>true will NOT result check for actual data, it only wants the field to be present in the data-array and "" is also considered as present