2016-05-31 26 views
0

我想在自定義窗體字段類型中獲取當前用戶。可捕獲的致命錯誤:傳遞給UserBundle Form UserType :: __ construct()的參數2必須是實例?

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

在控制器我打電話這樣的形式:

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

我得到這個以下錯誤:

Catchable Fatal Error: Argument 2 passed to UserBundle\Form\UserType::__construct() must implement interface Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface, none given, called in......

回答

0

UserType::__construct方法簽名在這裏有兩個參數,並且您只在服務聲明($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); 
相關問題