Symfony/FOS - 将用户id变量传递给表单Type

3 formbuilder symfony fosuserbundle

我尝试从CategoryType表单设置字段"author"的值.我希望它是来自使用FOS包登录的当前用户的用户ID.

我的CategoryType表单:

namespace My\CategoryBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CategoryType extends AbstractType
{
    private $userId;

    public function __construct(array $userId)
    {
        $this->userId = $userId;
    }

     /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('author')
            ->add('content')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'My\CategoryBundle\Entity\Category',
            'auteur' => $this->userId
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'my_categorybundle_category';
    }
}
Run Code Online (Sandbox Code Playgroud)

而我的控制器动作:

public function addAction()
{
    $category = new Category;
    $user = $this->get('security.context')->getToken()->getUser(); 
    $userId = $user->getId();

    $form = $this->get('form.factory')->create(new CategoryType(), array( 'author' => $userId));

    $request = $this->get('request');
    if ($request->getMethod() == 'POST') {
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($category);
            $em->flush();

        return $this->redirect($this->generateUrl('mycategory_voir',
            array('id' => $category->getId())));
        }
    }
    return $this->render('MyCategoryBundle:Category:add.html.twig',
        array(
            'form' => $form->createView(),
        ));
}
Run Code Online (Sandbox Code Playgroud)

我在运行动作时发现了这个错误:

可捕获致命错误:传递给My\CategoryBundle\Form\CategoryType :: __ construct()的参数1必须是数组,没有给定,在第55行的/My/CategoryBundle/Controller/CategoryController.php中调用,并在/ My/CategoryBundle中定义/Form/CategoryType.php第13行

它不是已经传递给表单的数组吗?

Pet*_*ley 10

你的问题就在这条线上

$form = $this->get('form.factory')->create(new CategoryType(), array( 'author' => $userId));
Run Code Online (Sandbox Code Playgroud)

你不满意合同My\CategoryBundle\FormCategoryType::__construct().在这里,让我们以另一种方式看待它.

$form = $this->get('form.factory')->create(
    new CategoryType(/* You told PHP to expect an array here */)
  , array('author' => $userId)
);
Run Code Online (Sandbox Code Playgroud)

作为第二个参数发送的数组Symfony\Component\Form\FormFactory::create()是最终作为$options数组注入的数组My\CategoryBundle\Form\CategoryType::buildForm()

在我看来,你有几种不同的方法可以解决这个问题

  1. 更新参数签名并调用My\CategoryBundle\FormCategoryType::__construct()以传递/接收整个用户对象(而不仅仅是他们的id - 请记住此时您正在使用Doctrine关系,而不是他们映射到的低级外键)

    namespace My\CategoryBundle\Form;
    
    use My\CategoryBundle\Entity\User; /* Or whatver your User class is */
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
    
    class CategoryType extends AbstractType
    {
        private $author;
    
        public function __construct( User $author )
        {
            $this->author = $author;
        }
    
    Run Code Online (Sandbox Code Playgroud)

    $form = $this->get('form.factory')->create(
        new CategoryType(
          $this->get('security.context')->getToken()->getUser()
        )
    );
    
    Run Code Online (Sandbox Code Playgroud)
  2. 不要将User类型注入到类型的构造函数中,只需让选项处理它

    namespace My\CategoryBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
    
    class CategoryType extends AbstractType
    {
        private $userId;
    
         /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('title')
                ->add('author', 'hidden', array('data'=>$options['author']))
                ->add('content')
            ;
        }
    
        /**
         * @param OptionsResolverInterface $resolver
         */
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'My\CategoryBundle\Entity\Category'
            ));
        }
    
        /**
         * @return string
         */
        public function getName()
        {
            return 'my_categorybundle_category';
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 甚至不打扰将作者放在表单中并让控制器处理它

    $form = $this->get('form.factory')->create(
        new CategoryType()
      , array('author' => $this->get('security.context')->getToken()->getUser() )
    );
    
    Run Code Online (Sandbox Code Playgroud)

    if ($request->getMethod() == 'POST') {
        $form->bind($request);
    
        if ($form->isValid()) {
            $category->setAuthor(
              $this->get('security.context')->getToken()->getUser()
            );
            $em = $this->getDoctrine()->getManager();
            $em->persist($category);
            $em->flush();
    
        return $this->redirect($this->generateUrl('mycategory_voir',
            array('id' => $category->getId())));
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将表单类型转换为服务,并使用DI容器注入安全上下文

    应用程序/配置/ config.yml

    services:
      form.type.my_categorybundle_category:
        class: My\CategoryBundle\Form\CategoryType
        tags:
          - {name: form.type, alias: my_categorybundle_category}
        arguments: ["%security.context%"]
    
    Run Code Online (Sandbox Code Playgroud)

    更新您的类型以接收安全上下文

    namespace My\CategoryBundle\Form;
    
    use Symfony\Component\Security\Core\SecurityContext;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
    
    class CategoryType extends AbstractType
    {
        private $author;
    
        public function __construct( SecurityContext $security )
        {
            $this->author = $security->getToken()->getUser();
        }
    
    Run Code Online (Sandbox Code Playgroud)

    然后在您的控制器中,使用其服务名称创建表单

    $form = $this->get('form.factory')->create('my_categorybundle_category');
    
    Run Code Online (Sandbox Code Playgroud)