Search code examples
symfonysymfony-validator

Symfony Form and different validation groups


I have a form called UserType, which is used in my controller when creating a new user:

$newUser = new User();
$form = $this->createForm(UserType::class, $newUser);
$form->submit($request->request->all());

Now, I would like to also have an update route where a form is used. The form might be a different one, since some properties is not possible to change after creation. Because of this, I would also like different validations in the Entity. How do I pass different validation groups through the form in my controller?


Solution

  • With the Option Resolver You can pass the group name validation as an option and get It in the UserType

    $newUser = new User();
    $form = $this->createForm(UserType::class, $newUser, ['validation'=>'your_validation_group_name']);
    $form->submit($request->request->all());
    

    and in the UserType

    public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('username', TextType::class, [
                    'validation'=> $options['validation'] //contains your_validation_group_name 
                ])
            ;
        }
        public function configureOptions(OptionsResolver $resolver)
            {
                $resolver->setDefaults(array(
                    'validation' => ''
                ));
            }