I
I
Ivan Antonov2016-02-29 16:29:12
symfony
Ivan Antonov, 2016-02-29 16:29:12

How to make a text field to select an entity in a form in Symfony 3?

In Symfony 2 it was like this:

<?php
namespace AppBundle\Form\Type;

use AppBundle\Form\DataTransformer\EntityToNumberTransformer;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class OfferImageType extends AbstractType
{
    private $manager;

    public function __construct(ObjectManager $manager)
    {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('main', 'hidden')
            ->add('sort', 'hidden')
            ->add('image', 'hidden');

        $builder->get('image')
            ->addModelTransformer(new EntityToNumberTransformer($this->manager, 'AppBundle:File'));
    }
}

But in Symfony 3, for the createForm method, you need to pass not a class object, but its name, so it is no longer possible to initialize the EntityManager in advance. What option does version 3 offer?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2016-02-29
@antonowano

Pass EntityManager as options:

/**
     * @inheritDoc
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired('manager');
        $resolver->setAllowedTypes('manager', array(
            ObjectManager::class
        ));
    }

$form = $this->createForm(FooType::class, $object, array(
    'manager' => $this->getDoctrine()->getManager(),
));

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->get('image')
            ->addModelTransformer(new EntityToNumberTransformer($options['manager'],  'AppBundle:File'));
    }

or register the form as a service:
app.type.foo:
        class: %app.type.foo%
        arguments:
            - "@doctrine.orm.entity_manager"
        tags:
            - { name: form.type }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question