Get Event In Controller When Any Model Does Not Validate

I’m using a controller that does a lot of database interaction based on a file that is posted to it. It parses the file and distributes the information in about 8 different models.

Is there a single way that the controller can register an event that is called should any of the model->save() calls have any validation errors?

I know I do that in the models, but I don’t want to do that. I want this specific controller get an event in this case. Is there a way to do that?

Doesn’t anyone use events?

Assuming you need all of the updates to succeed, can you not just wrap the calls in a transaction? You could use something like the code below.




    public function actionYour_action()

    {

        if (/* file was posted */)

        {

            // Prepare models here.


            $transaction = Yii::app()->db->beginTransaction();


            try

            {

                if (!$model1->save())

                    throw new Exception('Failed to save model 1');


                if (!$model2->save())

                    throw new Exception('Failed to save model 2');


                // etc...


                $transaction->commit();

                Yii::app()->user->setFlash('success', 'Operation successful');

                $this->refresh();

            }

            catch (Exception $ex)

            {

                $transaction->rollback();


                // Do something with $ex->getMessage() or model validation errors

            }

        }


        $this->render('yourView');

    }



Thanks for that, that’s almost exactly how I solved it right now. I was just hoping there was some way to get an event for save() failure.