Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get instance of entity repository in the Form (Type) class in Symfony 2?

Let's say I have ordinary *Type class:

class LocationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add(...)
            ...
    }
}

and one of the fields is a choice type. The values that need to be used as choice items are supposed to be retrieved from the database (from some particular entity repository).

So the question is: how to get the repository in the LocationType class? Is passing it through the constructor the only way to get it?

UPD:

I know about entity type but unfortunately I cannot use it, because my property is not and cannot be defined as one-to-one relation due to very complex relation conditions that Doctrine doesn't support (yet?). See How to specify several join conditions for 1:1 relationship in Doctrine 2 for additional details

like image 818
zerkms Avatar asked Feb 06 '12 21:02

zerkms


1 Answers

You can specify an entity field type as an option like so:

$builder
    ->add('foo', 'entity', array(
        'class'  => 'FooBarBundle:Foo',
        'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
             return $er->createQueryBuilder('q')->orderBy('q.name', 'ASC');
         },
     ));

EDIT: Actually the 'class' option is the only required field option. You can read a bit more about the entity field type here: http://symfony.com/doc/2.0/reference/forms/types/entity.html

Hope this helps.

EDIT:

Further to discussion below, here's an example

In the controller:

$entity = new Foo();
$type   = new FooType();

$er = $this->getDoctrine()
    ->getEntityManager()
    ->getRepository('FooBarBundle:Foo');

$form = $this->createForm($type, $entity, array(
    'foo_repository' => $er
));

The $options array is passed to the FooType::buildForm() method, so foo_repository should then be available in this method like so:

$er = $options['foo_repository'];

Symfony 4 and 5:

Symfony Form Types are services so you can use dependency injection:

class FooType extends AbstractType
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    private function getFooRepository(): FooRepository
    {
        return $this->entityManager->getRepository(Foo::class);
    }

    ...
}

or inject specific repository:

class FooType extends AbstractType
{
    private $fooRepository;

    public function __construct(FooRepository $fooRepository)
    {
        $this->fooRepository = $fooRepository;
    }

    ...
}
like image 132
Darragh Enright Avatar answered Nov 19 '22 16:11

Darragh Enright