Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii custom model errors

Tags:

php

yii

I am saving a model instance performing some actions in "beforeSave" model function.
I want to add some errors/messages to the model and then to get them in the controller and show to the user.
As far I have two ideas of how to implement this:

  • Use a dummy attribute with ActiveRecord function "addError": $this->addError("dummy"=>"my message"); It is not the best way to do it as I'll have to invent new dummy attributes.
  • Add a new property "custom_errors" to the model and function "addCustomErrors"

Maybe there is a built-in way to do it or an extension?
Anyway how can I do it?

like image 434
lvil Avatar asked Apr 25 '12 13:04

lvil


2 Answers

You can use the addError() but there's no need to make up fake attributes. If an error doesn't relate to anything on the model itself then your doing something wrong :p

So in your case it would be something like:

 $this->addError('file', 'Something happened I wasn\'t pleased with');

If there are any other errors on the file attribute they'll acumlate so you don't need to worry about overwriting.

like image 142
Paystey Avatar answered Nov 26 '22 19:11

Paystey


I don't see the problem here. Simply use addError() http://www.yiiframework.com/doc/api/1.1/CModel#addError-detail. The model is kept even after invoking save() on it, so you could just do something like

yourController()
{
   do_something();
   do_something();
   $model->save();
   $errors[]=do_what_you_have_to_do_to_define_the_errors_which_will_be_added();
   $model->addError(attribute, $errors);
   $this->render(viewWhereTheErrorWillBeDisplayed, $model);
}
like image 44
Alfredo Castaneda Garcia Avatar answered Nov 26 '22 18:11

Alfredo Castaneda Garcia