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?
From controller you have to pass user object to form builder
Then in form builder you can fetch it from
$options
:Don't forget to extend
setDefaultOptions()
withuser
index: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:And the form class like this:
I know this is an old question, but I'd like to put forward a better alternative for checking roles inside a form type.
The issue
The issue with using the TokenInterface and the User object is that it does not check for inheritance. For example, consider the following
security.yml
:If your user has
ROLE_SUPER_ADMIN
but notROLE_ADMIN
added to their roles, the above solutions will fail if you are using$user->hasRole('ROLE_ADMIN')
, as the user does not explicitly haveROLE_ADMIN
assigned to their user andhasRole()
does not check hierarchy.The solution
Use the
AuthorizationCheckerInterface
instead to gain access to theisGranted()
function.This will respect any hierarchy defined in
security.yml
. If we use the same yml file as above,$auth->isGranted('ROLE_ADMIN')
will return true if a user hasROLE_SUPER_ADMIN
but notROLE_ADMIN
assigned to their profile.