首页 文章

Symfony2:如何在不覆盖要编辑的实体的情况下将当前用户发送到编辑表单?

提问于
浏览
2

好的,所以我需要在表单中访问当前用户的角色,以便根据角色查询不同的东西,在创建新用户时它可以正常工作 . 将登录用户作为$ options发送到表单...但是,我注意到在编辑表单时,$ options中的$ data选项,它是要编辑的实体...

如何在不覆盖任何实体的情况下向实体发送当前用户进行编辑?

我在尝试这个:

$current_user = $this->get('security.context')->getToken()->getUser();
        $form = $this->createForm(new UserType(), $entity, array(
            'action' => $this->generateUrl('user_update', array('id' => $entity->getId())),
            'method' => 'POST',
            'data' => $current_user,
        ));

但'data'选项似乎覆盖了我上面发送的$实体 .

我怎么送两个?

1 回答

  • 2

    我认为要实现更高的质量水平,您需要将表单类型声明为服务,并将SecurityContext对象作为依赖项接收,如下所示:

    services:
        form.type.user:
            class: Acme\DemoBundle\Form\Type\UserType
            arguments: ["@security.context"]
            tags:
                - { name: form.type, alias: user_type }
    

    并声明这样的表单类型:

    class UserType extends AbstractType {
    
    
        private $securityContext;
    
        public function __construct(SecurityContext $securityContext)
        {
            $this->securityContext = $securityContext;
        }
    }
    

    这样您就可以通过SecurityContext对象访问用户,该对象将由Symfony自动注入 .

    像这样创建表单:

    $form = $this->createForm($this->get('form.type.user'), $data);
    

相关问题