Search code examples
phpmany-to-manysymfony-formssymfony

Symfony 3 form many-to-many


I'm trying to create a form where I can place an order. My database schema looks like this:

enter image description here

I would like to have a form like this:

enter image description here

This is what I have so far:

$order = new Order();

$form = $this->createFormBuilder($order)
    ->add('naam', TextType::class)
    ->add('email', EmailType::class)
    ->add('phoneNumber', TextType::class)
    ->add('dateTakeout', DateType::class)
    ->add('hourTakeout', DateType::class)
    ->add('save', SubmitType::class, array('label' => 'Verzenden'))
    ->getForm();

But I'm stuck with adding the products to my form. How can I do this?

UPDATE:

The connection of my product and category is like this:

enter image description here

I have a Category entity with id, name, enabled and parentCategoryId.

In my Product entity I have a category property.

I would like to show the categories and products like this:

enter image description here


Solution

  • Add this to your form:

    use Symfony\Component\Form\Extension\Core\Type\IntegerType;
    ...
    ->add('product_A', IntegerType::class)
    ->add('product_B', IntegerType::class)
    ->add('product_C', IntegerType::class)
    ->add('product_D', IntegerType::class)
    

    This is an Integer, so you can simply call:

    $prodA_amount = $form->get('product_A')->getData();
    

    to get the value...