Im trying to add a captcha using yii to my contact form, but there is some problem with validation.
My model
class ContactForm extends CFormModel
{
public $verifyCode;
public function rules()
{
return array(
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'captchaRequired'),
array('verifyCode', 'safe'),
);
}
}
Code in my controller
public function filters()
{
return array(
'accessControl',
);
}
public function accessRules()
{
return array(
array( 'allow', //allow all users to perform advertise and index action
'actions' => array('advertise','index', 'captcha'),
'users' => array('*'),
),
);
}
public function actions() {
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha' => array(
'class' => 'CCaptchaAction',
'backColor' => 0xFFFFFF,
'testLimit'=> '2',
),
)
}
public actionAdvertise()
{ $model = new ContactForm;
$model->scenario = 'captchaRequired';
if($model->validate()){
//some code
} else {
$this->render('advertise', array('model' => $model));
}
}
}
Code in my advertise.php view
<form action="" method="post">
<?php
$form=$this->beginWidget('CActiveForm',array(
'id'=>'contact-form',
'enableAjaxValidation'=>false,
));
?>
<?php if(CCaptcha::checkRequirements()){ ?>
<div class="row">
<div class="contact_field_wrapper">
<?php echo '<b>ARE YOU HUMAN?</b><br />'.$form->labelEx($model, 'verifyCode'); ?>
<div class="captcha user-captcha">
<?php $this->widget('CCaptcha',array( 'captchaAction'=>'site/captcha' ));
?>
<?php echo $form->error($model, 'verifyCode'); ?>
<?php echo '<br />'.$form->textField($model,'verifyCode'); ?>
<div class="hint">Please enter the letters as they are shown in the image above.<br/>
Letters are not case-sensitive.
</div>
</div>
</div>
</div>
<?php } ?>
<?php $this->endWidget(); ?>
</form>
The problem is that $model->validate()
returns false when correct code in inputted.
$model->getErrors()
is always returning 'Verification code is incorrect'.
your model is empty , because you didn't pass any value to $model->attriburtes
Do this :
if($_POST['ContactForm'])
{
$model->attributes() = $_POST['ContactForm'];
if($model->validate())
{
//some code
}
}
$this->render('advertise', array('model' => $model));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With