alison_feik
alison_feik

Reputation: 33

Symfony2 - Keep form validation after modifying field in SUBMIT event

I need to modify a field in the SUBMIT form event, but when I do any validation rules on the field are lost.

This is all that's happening in the form type (the title field isn't actually being changed I'm just using it as an example):

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add("title");

    $builder->addEventListener(FormEvents::SUBMIT, function(FormEvent $event) {
        $form = $event->getForm();

        $form->add("title");
    });
}

Any validation rules for 'title' are now lost, either annotation rules defined with the entity or using a separate validator class.

Can I do anything to keep the validation or is it intended that validation rules don't get run for fields which are modified in the SUBMIT event?

Upvotes: 0

Views: 760

Answers (2)

Martin Birks
Martin Birks

Reputation: 26

If you can handle the FormEvents::POST_SUBMIT event instead of FormEvents::SUBMIT you will keep the validation. You will need to make sure that the listener is on the child form that you want to edit, otherwise you will have an issue with not being able to add a field to a submitted form.

Upvotes: 1

user4545769
user4545769

Reputation:

In this instance you're not actually modifying a field you're adding a new one with $form->add('title') which will replace the existing 'title' field within the form (which is why the validation constraints are disappearing). You might want to look into validation groups for the type of functionality you're aiming for unless you want to elaborate on what you're doing within the submit event?

Upvotes: 0

Related Questions