Symfony/FOS-将用户ID变量传递给表单类型 [英] Symfony/FOS - pass the user id variable to a form Type

查看:76
本文介绍了Symfony/FOS-将用户ID变量传递给表单类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从CategoryType表单中设置字段作者"的值.我希望它是使用FOS软件包登录的当前用户的用户ID.

I try to set the value of a field "author" from a CategoryType form. I want it to be the user id from the current user logged in with FOS bundle.

我的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';
    }
}

和我的控制器操作:

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

我在执行操作时捕获了此错误:

I catch this error while running the action :

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

Catchable Fatal Error: Argument 1 passed to My\CategoryBundle\Form\CategoryType::__construct() must be an array, none given, called in /My/CategoryBundle/Controller/CategoryController.php on line 55 and defined in /My/CategoryBundle/Form/CategoryType.php line 13

已经不是我要传递给表单的数组了吗?

Isn't it already an array that I am passing to the form ?

推荐答案

您的问题就在这行

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

您不满足My\CategoryBundle\FormCategoryType::__construct()的合同.在这里,让我们换一种方式看.

You're not satisfying the contract for My\CategoryBundle\FormCategoryType::__construct(). Here, let's look at it another way.

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

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

The array that you send as the 2nd argument to Symfony\Component\Form\FormFactory::create() is what is ultimately injected as $options array My\CategoryBundle\Form\CategoryType::buildForm()

如我所见,您可以通过几种不同的方式来解决此问题

As I see it, you have a few different ways to resolve this

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

  1. Update the argument signature AND call for My\CategoryBundle\FormCategoryType::__construct() to pass/receive the entire user object (not just their id - remember that you're working with Doctrine relationships at this point, not the lower-level foreign keys that they map to)

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

$form = $this->get('form.factory')->create(
    new CategoryType(
      $this->get('security.context')->getToken()->getUser()
    )
);

  • 不要将User注入类型的构造函数中,只需让选项来处理

  • Don't inject the User into the type's constructor, just let the options handle it

    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';
        }
    }
    

  • 甚至不用费心把作者放在表单中,让控制器来处理

  • Not even bother putting the author in the form and let the controller handle it

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

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

  • 将您的表单类型转换为服务,并使用DI容器注入安全性上下文

  • Turn your form type into a service and user the DI Container to inject the security context

    app/config/config.yml

    services:
      form.type.my_categorybundle_category:
        class: My\CategoryBundle\Form\CategoryType
        tags:
          - {name: form.type, alias: my_categorybundle_category}
        arguments: ["%security.context%"]
    

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

    Update your type to receive the security context

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

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

    Then in your controller, create the form with its service name

    $form = $this->get('form.factory')->create('my_categorybundle_category');
    

  • 这篇关于Symfony/FOS-将用户ID变量传递给表单类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆