简体   繁体   English

Symfony 3-提交并验证后修改表单值

[英]Symfony 3 - Modify form value after submit and validation

In my application I have the requirement to modify a submitted and validated form value. 在我的应用程序中,我需要修改已提交并经过验证的表单值。

The use case is a form with an address that is validated and possibly corrected by an external web service. 用例是一种表单,其地址已由外部Web服务验证并可能得到纠正 I need to update the address in the form after the correction and inform the user about that in there newly rendered form. 我需要在更正后更新表单中的地址,并在新呈现的表单中通知用户有关地址。 The user should not get a validation error after correction. 校正后,用户不应收到验证错误。

Symfony's form component does not allow to modify an already submitted form value and throws an AlreadySubmittedException exception. Symfony的表单组件不允许修改已提交的表单值,并引发AlreadySubmittedException异常。

One solution is to pass the corrected address to the template and add logic to it. 一种解决方案是将更正的地址传递给模板,并向其添加逻辑。 But this is the wrong way in my opinion. 但是我认为这是错误的方式。

Is there another solution? 还有其他解决方案吗?

Thanks in advance, Jens 预先感谢,詹斯

Yes you're correct, passing the corrected value to the template is not the right way. 是的,您是正确的,将正确的值传递给模板不是正确的方法。

The correct way is to add an event listener to your form and validate/correct the value there. 正确的方法是将事件侦听器添加到窗体,然后在其中验证/更正值。

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('address');

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();
            // do webservice validation here and
            $data = [];

            // set new data
            $event->setData($data);
        });
    }
}

The docs for more information. 有关更多信息的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM