[英]Modifying Symfony form data after failed validation
I've got a Symfony form field with a custom validator. 我有一个带有自定义验证程序的Symfony表单字段。 If the user submits the form and validation fails, I'd like to correct the value and show it to the user for review.
如果用户提交表单,但验证失败,我想更正该值并将其显示给用户以供查看。
How can I modify a submitted form field after validation? 验证后如何修改提交的表单字段?
PRE_SUBMIT
isn't suitable as it's executed before the validation: PRE_SUBMIT
不适合,因为它在验证之前执行:
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) {
$data = $event->getData();
$data['myField'] = 'Modified!';
$event->setData($data);
});
I've also tried making the modification in the controller, but I get a You cannot change the data of a submitted form
error. 我也尝试在控制器中进行修改,但得到一个“
You cannot change the data of a submitted form
错误You cannot change the data of a submitted form
。
if ($form->isSubmitted() && !$form->isValid()) {
$form->get('myField')->setData('Modified!');
}
Is there any way of doing this? 有什么办法吗?
How is this way? 这样怎么样
$myValue = '';
if ($form->isSubmitted() && !$form->isValid()) {
$myValue = 'Modified!';
}
return $this->render('my_template.html.twig', [
'form' => $form->createView(),
'myValue' => $myValue,
]);
In my_template.html.twig
, 在
my_template.html.twig
,
{{ form_widget(form.myField, {'value' : myValue}) }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.