How display duplicate attribute error validation message in yii

1k Views Asked by At

I need display error message when user register end he input email which exist.I try this in my view:

<?php echo $form->errorSummary($model, NULL, NULL, array("class" => "standard-error-summary")); ?>

and this

if($model->hasErrors())
  echo CHtml::errorSummary($model);

But it doesn't work.

There is my rules method of User model

    public function rules()
{
    return array(
        array('status', 'numerical', 'integerOnly'=>true),
        array('first_name, last_name, email, password', 'length', 'max'=>255),
        array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
        array('id, status, first_name, last_name, email, password', 'safe', 'on'=>'search'),
    );
}

RegistrationForm Model:

    public function rules()
{
    return array(
        array('first_name, repeat_password, last_name, password,email', 'required'),
        array('email', 'email'),
        array('password', 'compare','compareAttribute'=>'repeat_password'),
      );
  } 

and my register action:

    public function actionRegister()
{
    $model = new RegistrationForm;
    if(isset($_POST['RegistrationForm']))
    {
        $model->attributes = $_POST['RegistrationForm'];
        if($model->validate())
        {
          $user = new User;
            $user->first_name = $model->first_name;
            $user->last_name = $model->last_name;
            $user->password = $model ->password;
            $user->email = $model->email;
            $user->save();
        }
    }
    $this->render('register',array('model'=>$model));
}
2

There are 2 best solutions below

0
YuriiChmil On

I found solution. I added this method in my RegisterationForm Model

public function uniqueEmail($attribute, $params)
{
    if($user = User::model()->exists('email=:email',array('email'=>$this->email)))
        $this->addError($attribute, 'Email already exists!');
}

and added

array('email', 'uniqueEmail','message'=>'Email already exists!'),

to the rules method

0
Taron Saribekyan On

Such as you validate RegistrationForm model, you must have unique rule in it (not onlu in User model). So you can add this rule in your RegistrationForm model too:

public function rules()
{
    return array(
        array('first_name, repeat_password, last_name, password,email', 'required'),
        array('email', 'email'),
        // THIS RULE CHECKS EMAIL UNIQUE IN RegistrationForm MODEL
        array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
        array('password', 'compare','compareAttribute'=>'repeat_password'),
      );
} 

So not not necessary to add custom rule.

Thanks!