How can i access the user Role in Form Builder class in Symfony2

前端 未结 1 977
梦毁少年i
梦毁少年i 2020-12-11 01:08

I have the form as UserType with field like this

->add(\'description\')
  ->add(\'createdAt\')

Now i want that if the Lo

相关标签:
1条回答
  • 2020-12-11 01:32

    Pretty simple. Just make your custom form type a service, depending on the security context:

    use Symfony\Component\Security\Core\SecurityContext;
    
    class UserType extends AbstractType
    {
    
        private $securityContext;
    
        public function __construct(SecurityContext $securityContext)
        {
            $this->securityContext = $securityContext;
        }
    
        public function buildForm(FormBuilder $builder, array $options)
        {
            // Current logged user
            $user = $this->securityContext->getToken()->getUser();
    
            // Add fields to the builder
        }
    
        public function getDefaultOptions(array $options)
        {
            return array(
                'required'   => false,
                'data_class' => 'Acme\HelloBundle\Entity\User'
            );
        }
    
        public function getName()
        {
            return 'user_type';
        }
    }
    

    Then mark the class as a service, with the special tag form.type:

    services:
        form.type.user:
            class: Acme\HelloBundle\Form\Type\UserType
            arguments: ["@security.context"]
            tags:
                - { name: form.type, alias: user_type }
    

    In your controller, instead of doing new UserType(), grap the service from the container:

    $form = $this->createForm($this->get('form.type.user'), $data);
    
    0 讨论(0)
提交回复
热议问题