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

杀马特。学长 韩版系。学妹 提交于 2019-12-22 08:26:50

问题


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(),
));

回答1:


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.




回答2:


To make the first simple (without dependency injection) Transformer's cookbook recipe work you should add "em" as a known option. You can add it in your form's type class (TaskType in cookbook case) using setRequired() method like this:

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() would also work, but in this cookbook case entity manager is needed and so using setRequired() seems better.




回答3:


dont 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',
    ));


来源:https://stackoverflow.com/questions/11605530/symfony2-1-the-option-em-does-not-exist-when-using-datatransformer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!