Add An Error Before Save() In Action

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?

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)));

}



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.

Works great, thank you! Thank you for the explanation and sorry for doubting you ;)