Condition if ($post->save()) failed

Hi guys,

How to write a condition if the $post->save()is failed and throw a error msg?? my condition write like this, how to throw a error message (404, ‘The user already exist.’)if the $model->save() is failed.




 if(!$model->save())

                {

                    throw new CHttpException(404, 'The user already exist.');

                }

                if($model->save())

                {

                    $this->render('index');

                }



thank… =)

How about this:




if($model->save())

{

    $this->render('index');

} 

else

{

    throw new CHttpException(404, 'The user already exist.');

}



But it would be better to use validations to get this error and to display a nice error/warning message on the input form.

Hi mdomba,

I already try your suggestion but it wont show (404, ‘The user already exist.’);

but show a page about sql statement message about the duplicate entry… I plan to use validation to show error message but struck in half way.

How to set the validation in model view? How to check and match with database?


array('email','checkExists')




  public function checkExists($attribute, $params) {

   $info=user::model()->findByAttributes(array('email'=>$model->email));

        if ($this->email== $info->email)

            $this->addError('email', 'email exists!');

    }



Please Help… Thx. =)

Yes, you get the error because mysql fires it… so the best solution is to use validation…

Yii has the CUniqueValidator - http://www.yiiframework.com/doc/api/1.1/CUniqueValidator

use it as


array('email','unique'),

Thank mdomba for reply.

How to check the email whether already exist in database. what condition need put at the model view to show the error message when the email is already exist. Am my code is correct or totally wrong?


  public function checkExists($attribute, $params) {

   $info=user::model()->findByAttributes(array('email'=>$model->email));

        if ($this->email== $info->email)

            $this->addError('email', 'email exists!');

    }

Thank… XD

There is no need for a custom method if there already exists one in Yii like I answered you above…

As for your method… what is the value of $model->email in your method ?

hi mdomba,

for sign up form, it will check whether the email already exist or not, then it will throw a error message if email already exist in DB, else will success save to DB.


  

For rule: 

array('email','checkExists')




 public function checkExists($attribute, $params)

    {

        $post = user::model()->findByAttributes(array('email' => $this->email));

        if($post->email == $this->email)

        {

            $this->addError('email', 'The email already been used!');

        }

    }

thanks.