1
votes

I'm trying to save data with field that has validation isUnique rule but having issue when trying to update via below method.

$this->Model->id = 1; 
$this->Model->save($this->data);

If I do above, this generates validation error saying I'm only allowed to have unique value but I'm trying to update this instead.

Is there a way around this issue?

2
what happens if you pass the id in the data array along?mark

2 Answers

2
votes

That looks ok to me; Cake will attempt to update a record with the primary key of id when it's manually set like that.

Do a search in your table with the supposedly "unique" data; and see if any other result can be found. It's possible you have duplicate data that was in use before you introduced the isUnique validation rule.

Are you doing this update within a loop?

You could possibly try changing the on validation rule in your model to create, preventing it from triggering on an update; but I'm not sure that should be necessary; plus you could then update a record with duplicate information, defeating the purpose!

var $validate = array(
    'fieldName1' => array(
        'rule' => 'isUnique',
        'required' => true,
        'allowEmpty' => false,
        'on' => 'create', // here
        'last' => false,
        'message' => 'Your Error Message'
    )
);
1
votes

Just pass the id along with the array. Like:

$this->create();
$data['id'] = $id;
$this->save($data);