symfonyformbuilderrole

how to check the user role inside form builder in Symfony2?


Okay, i'm trying to check if an user has a specific role, i did this

however, when i do this:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder
        ->add('nombre',null,array('label' => 'Usuario'))
        ->add('email')
        ->add('password', 'repeated', array(
            'type' => 'password',
            'invalid_message' => 'Los campos deben coincidir',
            'first_name' => 'password',
            'second_name' => 'confirmar password',
            'options' => array('required' => false)
            ))

        ->add('cliente', 'entity', array(
        'class' => 'ClientesBundle:Cliente',
        'empty_value' => 'Company',            
        'required'    => false,
        'empty_data'  => null)
    **)**
      $user = $this->securityContext->getToken()->getUser();
      **if ($user->getRol() == 'ROLE_SUPER_ADMIN'){**
        ->add('rol') 
        **}**
    ;

}

tried this as well:

 **if ($this->securityContext->getToken()->getUser()->getRol() === 'ROLE_SUPER_ADMIN'){**
            ->add('rol') 
            **}**

the bolded lines (the ones with **) have the tiny red line that indicates an error, and it's says unexpected if... How do i fix this?


Solution

  • From controller you have to pass user object to form builder

    $form = $this->createForm(
        new YourType(), 
        $data, 
        array('user' => $this->getUser())
    );
    

    Then in form builder you can fetch it from $options:

    public function buildForm(FormBuilder $builder, array $options)
    {
        $user = $options['user']
    }
    

    Don't forget to extend setDefaultOptions() with user index:

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            ...
            'user' => null
        ));
    }