0

当用户注册结束时我需要显示错误消息,他输入了存在的电子邮件。我在我的视图中尝试这个:

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

和这个

if($model->hasErrors())
  echo CHtml::errorSummary($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'),
    );
}

报名表型号:

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

和我的注册操作:

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

2 回答 2

2

例如您验证RegistrationForm模型,您必须unique在其中有规则(而不是User模型中的唯一)。因此,您也可以在RegistrationForm模型中添加此规则:

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'),
      );
} 

所以没有必要添加自定义规则。

谢谢!

于 2015-07-03T10:40:17.370 回答
0

我找到了解决方案。我在我的 RegisterationForm 模型中添加了这个方法

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

并添加

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

到规则方法

于 2015-07-01T07:20:52.987 回答