php - Symfony - Optimize form with repetitive EntityType

one text

Solution:

One way of doing that would be to to create a property $clientChoices where you store once and for all your repo->getAll() result. For that, you have to define your form as a service : https://symfony.com/doc/3.4/form/form_dependencies.html.

You would then inject the EntityManager to get what you want in the constructor, something like this:

<?php

namespace AppBundle\Form;

/*****
** Here all my others 'use'
*****/

use AppBundle\Entity\Contact;
use AppBundle\Repository\ContactRepository;

class EventForm
{
    private $clientChoices = [];

    public function __constructor(EntityManagerInterface $entityManager)
    {
        $this->clientChoices = $entityManager->getRepository(Client::class)->getAll();
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            
        // A lot of ->add(), not revelant for my issue
        
        ->add('client1', EntityType::class, [
            'class' => Client::class,
            'choices' => $this->clientChoices,
        ])
        
        ->add('client2', EntityType::class, [
            'class' => Client::class,
            'choices' => $this->clientChoices,

            }
        ])
        
        // ->add('client3'), same as above
        // ->add('client4'), same as above
        // ->add('client5'), same as above
        // ->add('client6'), same as above

        ;

    }

Source