Zaid Mirza
Zaid Mirza

Reputation: 3709

Dynamic CollectionType in Symfony FormType

I have one Parent and three child FormTypes:

ParentFormType

ChildOneFormType ChildTwoFormType ChildThreeFormType

All thee child classes inherit from parent.

So, here is my Form class

 class MyFormType extends AbstractType
 {
     /**
      * @param FormBuilderInterface $builder
      * @param array $options
      */
     public function buildForm(FormBuilderInterface $builder, array $options)
     {
         $builder
             ->add('name', TextType::class, [
                 'constraints' => [new NotBlank()]
             ])
             ->add('description', TextType::class, [
                 'required' => false
             ])
             ->add('wallets', CollectionType::class, [
                 'entry_type' => ParentFormType::class, // Issue is here when wallet is one of the child class
                 'allow_add' => true,
             ]);
     }

     /**
      * @param OptionsResolver $resolver
      */
     public function configureOptions(OptionsResolver $resolver): void
     {
         $resolver->setDefaults([
             'data_class' => MyFormClass::class,
             'allow_extra_fields' => true,
             'csrf_protection' => false
         ]);
     }

     /**
      * @return string
      */
     public function getName(): string
     {
         return 'MyForm';
     }
 }

Wallets can contain data related to any child class, but Form is not validated it because validation is being done only on fields added on ParentFormType.

So, how I can pass and validate this type of dynamic CollectionType?

Upvotes: 0

Views: 38

Answers (0)

Related Questions