我正在尝试进行自定义验证。除 $ this-> addError 外,所有工作正常。
它没有添加错误。这是我的控制器动作
public function actionVerifyAnswer()
{
if(isset(Yii::app()->session['_emailId']))
{
$model=new LoginForm;
$model->scenario='verifyAns';
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
if($model->validate())
{
$theQuestion=$model->secretQuestion;
$theAnswer= strtolower($model->verifyAnswer);
$usersModel=new Users;
$emailUser= Yii::app()->session['_emailId'];
$userRecord=$usersModel->find('loginEmail=:email AND secretQuestion=:que',array(':email'=>$emailUser,':que'=>$theQuestion));
if(empty($userRecord))
{
throw new CHttpException('You have selected the wrong question');
}
else
{
$usersAnswer= strtolower($userRecord->secretAnswer);
if($theAnswer === $usersAnswer)
{
$this->redirect('changePassword');
}
else
{
throw new CHttpException('you have given the wrong answer');
}
}
}
else
{
throw new CHttpException('model->validate()');
}
}
else
{
$secretQuestion= Yii::app()->params['secretQuestion'];
$this->render('verifyAnswer', array('model'=>$model,
'secretQuestion'=>$secretQuestion,
));
}
}
else
{
Yii::app()->user->loginRequired();
}
}
这是模型
中的自定义验证public function checkQuestion()
{
if(!$this->hasErrors())
{
$model=new LoginForm;
$theQuestion=$this->secretQuestion;
$usersModel=new Users;
$emailUser= Yii::app()->session['_emailId'];
$userRecord=$usersModel->find('loginEmail=:email AND secretQuestion=:que',array(':email'=>$emailUser,':que'=>$theQuestion));
if(empty($userRecord))
{
//this line is not working
$this->addError('secretQuestion', 'Incorrect Combination');
//if i throw exception here. Then exception is working
}
}
}
如何使$ this-> addError正常工作?
答案 0 :(得分:0)
应从模型验证中触发自定义验证;
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('the_answer', 'checkQuestion'),
....
);
}
public function checkQuestion($attribute,$params)
{
....
if(empty($userRecord))
{
//this line is not working
$this->addError('secretQuestion', 'Incorrect Combination');
//if i throw exception here. Then exception is working
}
}
答案 1 :(得分:0)
我已经解决了这个问题,我正在发布答案,因为它也可以帮助其他人。 我需要删除
else{
//not the code inside
}
这种情况
if(isset($_POST['LoginForm']))
{
注意: - 我刚删除其他及其大括号{} ,将代码留在其他
中因为它是,即: -
$secretQuestion= Yii::app()->params['secretQuestion'];
$this->render('verifyAnswer', array('model'=>$model,
'secretQuestion'=>$secretQuestion,
));