I am trying to do the custom validation.All is working fine except $this->addError .
It is not adding the error as it should. this is my controller action
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();
}
}
and this is my custom validation in the model
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
}
}
}
How can i make $this->addError working?
I have solved the issue and i am posting the answer because it might help somebody else also. I needed to remove the
else{
//not the code inside
}
of this condition
if(isset($_POST['LoginForm']))
{
Note:- I just removed the else and its braces {} and left the code inside the else
as it was i.e :-
$secretQuestion= Yii::app()->params['secretQuestion'];
$this->render('verifyAnswer', array('model'=>$model,
'secretQuestion'=>$secretQuestion,
));
Custom validation should be triggered from within the model validate ;
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
}
}