Search code examples
symfony-3.4

Form builder for a related entity Symfony 3


Well let's say I have 2 entities:

  1. category
  2. product

I want to create a form builder for the entity product in which there is a select to choose the category of the product.

How can I do that with Symfony 3.4?

Can you guys give me an example?


Solution

  • You want to use the EntityType.

    See below for an example:

    use Symfony\Bridge\Doctrine\Form\Type\EntityType;
    use Doctrine\ORM\EntityRepository;
    // ...
    
    ->add('category', EntityType::class, [
        'class'         => 'AppBundle:Category',
        'multiple'      => false,
        'expanded'      => false,
        'choice_label'  => 'title',
        'query_builder' => function (EntityRepository $er) {
            // use query builder for ordering/filtering choices
            return $er->createQueryBuilder('cat')
                ->orderBy('cat.title', 'ASC');
        },
    ])
    

    I assume your category entity has a property called title. This would be in your Product form type class.