ZF2 Captcha check is ignored when using input filter
I have a form in my ZF2 application with a CAPTCHA element like this:
$this->add(array(
'type' => 'Zend\Form\Element\Captcha',
'name' => 'captcha',
'attributes' => array(
'class'=>'form-control',
),
'options' => array(
'label' => 'Please verify you are human.',
'captcha' => array('class' => 'Dumb')
),
));
I have an input filter attached to a form that validates other elements in the form (name, email, message). When it is attached to a form, validation for the CAPTCHA field is ignored on validation.
if ($request->isPost()) {
// set the filter
$form->setInputFilter($form->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) { ...
If I remove the input filter, then the CAPTCHA field is validated correctly, but obviously the other fields don't have validators. What stupid mistake am I making? Is there a way to validate the "CAPTCHA" that I have to set in the input filter?
source to share
The problem is I am assuming that in your form, you have created a method called:
getInputFilter ();
which overrides the original getInputFilter (),
there are two solutions:
rename your function in your form to get getInputFilterCustom ()
and then change also:
if ($request->isPost()) {
// set the filter
$form->setInputFilter($form->getInputFilterCustom());
or inside your current getInputFilter () add logic to validate captcha.
source to share
This is my code for adding captcha image control in ZF2 form:
$this->add(array(
'name' => 'captcha',
'type' => 'Captcha',
'attributes' => array(
'id' => 'captcha',
'autocomplete' => 'off',
'required' => 'required'
),
'options' => array(
'label' => 'Captcha :',
'captcha' => new \Zend\Captcha\Image(array(
'font' => 'public/fonts/arial.ttf',
'imgDir' => 'public/img/captcha',
'imgUrl' => 'img/captcha'
))
),
));
Other form elements use validators from the input filter, but I haven't used any validators to get it to work.
Hope this helps you.
source to share