Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Splendonia Avatar asked Jan 29 '13 15:01

Splendonia


2 Answers

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
    ));
}
like image 189
Vitalii Zurian Avatar answered Sep 23 '22 08:09

Vitalii Zurian


If you declare your form type as a service, you can inject the token storage in your class.

So you declare the service in services.yml like this:

my_form:
    class: AppBundle\Services\MyFormType
    public: true
    arguments:  ['@security.token_storage']

And the form class like this:

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class MyFormType extends AbstractType
{
    protected $tokenStorage;

    public function __construct(TokenStorage $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $user = $this->tokenStorage->getToken()->getUser();
        // Use the user object to build the form
    }
}
like image 31
mavroprovato Avatar answered Sep 22 '22 08:09

mavroprovato