0
votes

I am trying to get the current user in a Custom Form Field Type.

My 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',))........
                 ....

Here is my service:

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

In the Controller I am calling the form like this:

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

I am getting this following error:

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......

1

1 Answers

0
votes

The UserType::__construct method signature has two parameters here, and you're only passing one in your service declaration ($doctrine), hence the error. If you still need Doctrine in the form type, you should pass it as well:

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

Also, looks like you're not creating the form itself correctly, instead of instantiating the type itself, you should just pass its class name, as explained by Christophe Coevoet:

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