Consider following Order 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 handle the form in Symfony 3.2?
[ 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;
}
}
I don't know how to write the RequirementType
, as they are not exactly the same (size, shape, color, ...).
This is 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;
}
}
If I correctly understand, the requirement’s attributes ("Small", "Medium", "Large"…) are stored in the Collection’ table, and are related to the requirement (“sizes”, “shapes”, “colors” …) with a oneToMany relation (a requirement can have multiple selection) ….
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 your 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) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With