Searched for a long time and found a similar issue with one possible work around.
Similar problem thread
However, JmZ’s unsafe but working solution does not work in my situation. I will recap so that the issue is all located in one place.
I am running into an issue where I want to initiate an error if there are two, not unique field values. I have a rule like this in my model:
Model.php
public function rules(){
return array(
...
array('field_1', 'unique','criteria'=> array(
'condition'=> 'field_2=:field_2',
'params'=>array(':field_2'=>$this->field_2)
))
);
}
This rule works fine for me if all assignments are single field assigments.
- DOESN’T WORK
$myModel = new Model;
$myModel->attributes = $_POST['notUniqueFields'];
$myModel->field_2 = notUnique2;
//saves a duplicate model ($this->field_2 is null in validation)
$myModel->save(); //or validate();
- DOESN’T WORK — though works for JmZ
$myModel = new Model;
$myModel->field_2 = notUnique2;
$myModel->attributes = $_POST['notUniqueFields']; //<-----error here
$myModel->save(); //or validate();
3)Works but can become difficult to manage with large number of fields
$myModel = new Model;
$myModel->field_1 = $_POST['notUniqueFields']['notUnique1'];
$myModel->field_2 = notUnique2;
//this generates error as I would expect.
$myModel->save(); //or validate();
Actually duh, I was able to get #2 to work if I created a scenario and created a rule on ‘create’ that labels ‘field_2’ unsafe. His mentioning that this was not a safe solution got me thinking.
I guess this may be an acceptable solution, though I’d still like to understand why. I also tried the suggestion from the last post on that thread (#6 as of this post).
$_POST['notUniqueFields']['notUnique2'] = 6
$model->attributes = $_POST['notUniqueFields'];
$model->save(); //or validate
The above does not work. This leads me to believe that there is something with the way
setAttributes()
works.
Any insight any one?
And thanks!!