skyer2000
(Chadhuntley)
December 11, 2012, 5:49pm
1
I’m trying to use the following code to manually add validation rules in an action before saving the model. Unfortunately it looks like save() ignores addError().
$model->attributes=$_POST['Object'];
$model->addError('content', 'This is an error');
if($model->save())
{
$this->redirect(array('update','id'=>$model->id)));
}
How can I add errors like this before $model->save() so that validation fails? Without doing it in the model?
What do your model attribute rules look like?
skyer2000
(Chadhuntley)
December 11, 2012, 5:59pm
3
I’m trying to avoid using model attribute rules, as they will not work since I’m working with an EAV-ish database structure.
Not sure, but try:
$model->attributes=$_POST['Object'];
$model->addError('content', 'This is an error');
if($model->validate(null, false) && $model->save(false))
{
$this->redirect(array('update','id'=>$model->id)));
}
skyer2000
(Chadhuntley)
December 11, 2012, 6:52pm
5
compact_corpse:
Not sure, but try:
$model->attributes=$_POST['Object'];
$model->addError('content', 'This is an error');
if($model->validate(null, false) && $model->save(false))
{
$this->redirect(array('update','id'=>$model->id)));
}
I do not believe that will work, as that is turning off validation all together.
It will turn off validation after validating the model. Calling $model->validate(null, false) with validate without clearing errors. If you look at the source code here - http://www.yiiframework.com/doc/api/1.1/CModel#validate-detail , you’ll see the validate() function calls clearErrors() (http://www.yiiframework.com/doc/api/1.1/CModel#clearErrors-detail ) which resets all model errors, ie. clearing the error you just set, and then performs validation through your model’s rules.
skyer2000
(Chadhuntley)
December 11, 2012, 8:57pm
7
Works great, thank you! Thank you for the explanation and sorry for doubting you