Symfony CollectionType with different fields

Question:

Consider the following Order a form with so many requirements :

Title: [_________________] REQUIREMENTS: What sizes? [X] Small [X] Medium [_] Large What shapes? [_] Circle [X] Square [_] Triangle What colors? [X] Red [_] Green [X] Blue . . . 

How can I generate and process a form in Symfony 3.2 ?

What I think:

[Order] ------ OneToMany ------ [Requirement] ------ OneToMany ------ [Selection]

OrderType

 class OrderType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $form = $builder ->add('title', TextType::class, array()); ->add('requirements', CollectionType::class, array( 'entry_type' => RequirementType::class ) ) ->add('submit', SubmitType::class, array((); return $form; } } 

Problem

I don’t know how to write RequirementType since they are not exactly the same ( size , , color , ...).

That's what I think:

RequirementType

 class RequirementType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $form = $builder ->add(??????, EntityType::class, array( 'label' => ??????, 'expanded' => true, 'multiple' => true, 'class' => Selection::class, 'query_builder' => call_user_func(function (EntityRepository $er, $requirement) { return $er->createQueryBuilder('s') ->where('s.requirement = :requirement') ->setParameter('requirement', $requirement) },$em->getRepository($args['class']), $requirement); ) ); return $form; } } 
+5
source share
1 answer

If I understand correctly, the requirements attributes ("Small", "Medium", "Big" ...) are stored in the "Collection" table and are associated with the requirement ("dimensions", "shapes", "colors" ...) with oneToMany relation (a requirement may have multiple choices) ....

If so, the following code works:

OrderType.php

 $builder ->add('requirements', CollectionType::class, array( 'entry_type' => RequirementType::class ) ); 

RequirementType.php:

 $builder ->add('name', HiddenType::class, array('disabled'=>true)) ->add('collections', EntityType::class, array( 'class' => 'AppBundle:Collection', 'choice_label' => 'name', 'multiple' =>true)) 

In Twig view:

 {{ form_start(orderForm) }} {% for requirement in orderForm.requirements %} <label>{{ requirement.name.vars.value }}</label> {{ form_widget(requirement.collections) }} {{ form_widget(requirement.name) }} <br> {% endfor %} {{ form_end(orderForm) }} 
+1
source

Source: https://habr.com/ru/post/1261846/


All Articles