Zend Framework 2 - Removed form element causes validation to fail

…衆ロ難τιáo~ 提交于 2019-11-27 23:15:52

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()) {
    ...
lluisaznar

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.

daoerji

In class ValidatorChain implements Countable, ValidatorInterface, add a new method:

public function remove($name){
    foreach ($this->validators as $key => $element) {
        $validator = $element['instance'];
        if($validator instanceof $name){
            unset($this->validators[$key]);
            break;
        }
    }   
}

Use like this:

$form->getInputFilter()->get("xxxxx")->getValidatorChain()->remove('xxxxxx');

There must be a validator defined for this particular element that you are trying to remove.

In your controller where you are adding new elements to form, there must be addValidator calling like:

$element->addValidator('alnum');

That is actually causing validation to be failed. So you have removed the element from form but you still have validation defined on that element to be checked.

If you are not able to find this validation adding function in controller, try to see if it has been defined through config file.

You can read further about form validation in zf here: http://framework.zend.com/manual/1.12/en/zend.form.elements.html

I remove the element with:

$form->get('product')->remove('version');

When I post the form I disable the validator on this element with :

$form->getInputFilter()->get('product')->get('version')->setRequired(FALSE);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!