简体   繁体   中英

Modifying Symfony form data after failed validation

I've got a Symfony form field with a custom validator. 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:

$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.

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 ,

{{ form_widget(form.myField, {'value' : myValue}) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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