可捕获致命错误:传递给UserBundle \ Form \ UserType :: __ construct()的参数2必须是实例?

时间:2016-05-31 19:00:55

标签: php symfony security doctrine

我正在尝试将当前用户置于自定义表单字段类型中。

我的formType

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class UserType extends AbstractType {

  protected $doctrine;
  protected $tokenStorage;

public function __construct($doctrine,TokenStorageInterface $tokenStorage)
{
    $this->tokenStorage = $tokenStorage;
    $this->doctrine = $doctrine;
}


public function buildForm(FormBuilderInterface $builder, array $options)
{

$user = $this->tokenStorage->getToken()->getUser();
  $builder
    ->setAction($options['data']['url'])
    ->setMethod('GET')
            ->add('userType', 'choice', array('choices' => array(
                'userType_p' => $pId,
                'userType_t' => $tId),
                'choices_as_values' => true, 'label' => 'Usertype ',
                'expanded' => true, 'multiple' => true,
                'translation_domain' => 'User',))........
                 ....

这是我的服务:

  user.form.token:
  class: UserBundle\Form\UserType
  arguments: ['@security.token_storage']
  tags:
      - { name: form.type }

在Controller中,我调用的形式如下:

  $form = $this->createForm(new UserType($em,$this->get('user.form.token')), $data....

我收到以下错误:

  

捕获致命错误:传递给UserBundle \ Form \ UserType :: __ construct()的参数2必须实现接口Symfony \ Component \ Security \ Core \ Authentication \ Token \ Storage \ TokenStorageInterface,没有给出,在.....中调用

1 个答案:

答案 0 :(得分:0)

此处UserType::__construct方法签名有两个参数,您只需在服务声明($doctrine)中传递一个参数,因此会出错。如果你仍然需要表单类型中的Doctrine,你也应该传递它:

user.form.token:
  class: UserBundle\Form\UserType
  arguments: ['@doctrine', '@security.token_storage']
  tags:
    - { name: form.type }

另外,看起来你并没有正确创建表单本身,而不是实例化类型本身,你应该只传递它的类名explained by Christophe Coevoet

$form = $this->createForm(UserType::class, $data);