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

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

Is this another sure way to submit an entity manager to a form type?

 $taskForm = $this->createForm(new TaskType(), $task, array( 'em' => $this->getDoctrine()->getEntityManager(), )); 
+4
source share
3 answers

Although I cannot comment if this is the best way or not, I 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())); 

Type of form

 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; } // ... } 

Once my form types have any dependencies, I use the container to manage them. I personally find this method much clearer of what is going on and what my custom classes require than relying on Symfonyโ€™s complex form configuration to do this for me.

+4
source

To make the first simple (no dependency on injection) transformer recipe, you must add "em" as a known option. You can add it to your form type class (TaskType in the case of the cookbook) using the setRequired() method as follows:

 class TaskType extends AbstractType { //... public function setDefaultOptions(OptionsResolverInterface $resolver) { //...other stuff like $resolver->setDefaults(... if you need it $resolver->setRequired(array('em')); } } 

Adding "em" with $ resolver-> setDefaults () will also work, but in this case the cookbook entity manager is needed, and so using setRequired () looks better.

+9
source

Do not forget

 public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Acme\TaskBundle\Entity\Task', )); $resolver->setRequired(array( 'em', )); $resolver->setAllowedTypes(array( 'em' => 'Doctrine\Common\Persistence\ObjectManager', )); 
+2
source

All Articles