Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 - Removed form element causes validation to fail

I use a certain form in several places. In one of them I need to ignore a form element which I set programmatically after the validation.

Because it's just an exception I don't want to create a new form. So I thought, I just remove this element in the controller like:

$myForm->remove('myElement');

The problem is that the form now won't validate. I don't get any errors but the $myForm->isValid() just returns an empty value.

Any ideas what I might be doing wrong?

Thanks!

like image 365
Ron Avatar asked Apr 03 '13 08:04

Ron


2 Answers

Ok, finally I found a solution! You can define a ValidationGroup which allows you to set the attributes you'd like to validate. The others are not validated:

$form->setValidationGroup('name', 'email', 'subject', 'message');
$form->setData($data);
if ($form->isValid()) {
    ...
like image 157
Ron Avatar answered Nov 06 '22 13:11

Ron


The first thing I thought about was to remove the validator from your myElement's ValidatorChain. You could get it within the controller with:

$form->getInputFilter()->get( 'myElement' )->getValidatorChain()

It seems like you can't remove from the ValidatorChain, just add. Check this post. Matthew Weier O'Phinney, from Zend, explains why it can't be done and a possible solution for your scenario.

The way I solve this problem, is checking the 'remove condition' when I create the validator in the FormFilter class. If you use annotations I think it doesn't works for you, so Matthew suggestions is the one you should use.

Or you could try the one in this post from @Stoyan Dimov: define two forms, a kind of BasicForm and ExtendedForm. The first one have all the common form elements, the second one is an extended one of the other with the rest of fields. Depending on your condition you could use one or another.

like image 2
lluisaznar Avatar answered Nov 06 '22 15:11

lluisaznar