Search code examples
symfony-2.1data-transfer-objects

Symfony2.1 - The option "em" does not exist when using DataTransformer


I am using this cookbook recipe to add a data transformer in Symfon 2.1, but I am getting the following error, The option "em" does not exist. Known options are: "attr", "block_name",....

Is this still a valid way to send the entity manager over to the form type?

$taskForm = $this->createForm(new TaskType(), $task, array(
    'em' => $this->getDoctrine()->getEntityManager(),
));

Solution

  • While I can't comment if that's the best way or not, I've always passed them to my task constructor as a hard dependency...

    Services

    services:
        my_bundle.form.type.task:
            class: Company\MyBundle\Form\Type\TaskType
            arguments:
                - @doctrine.orm.entity_manager
    

    Controller

    $form = $this->createForm($this->get('my_bundle.form.type.task'), $task);
    // or
    $form = $this->createForm(new TaskType($this->getDoctrine()->getEntityManager()));
    

    Form Type

    namespace Company\MyBundle\Form\Type;
    
    use Doctrine\ORM\EntityManager;
    use Symfony\Component\Form\AbstractType;
    // ...
    
    class TaskType extends AbstractType
    {
        protected $em;
    
        public function __construct(EntityManager $em)
        {
            $this->em = $em;
        }
    
        // ...
    }
    

    As soon as my form types have any dependencies, I use the container to manage them. I personally find this method much more clear of what's going on, and what my custom classes require than relying on Symfony's complex form configuration to do it for me.