I want to know if a user has the 'VIEW_GEOLOC_DATA' role, but I have a problem using the twig function
is_granted()
Roles : {{ dump(app.user.getRoles()) }}
is_granted('ROLE_SUPER_ADMIN') : {{ dump(is_granted('ROLE_SUPER_ADMIN')) }}
is_granted('VIEW_GEOLOC_DATA') : {{ dump(is_granted('VIEW_GEOLOC_DATA')) }}
array(2) {
[0]=>
string(16) "ROLE_SUPER_ADMIN"
[1]=>
string(16) "VIEW_GEOLOC_DATA"
}
is_granted('ROLE_SUPER_ADMIN') : bool(true)
is_granted('VIEW_GEOLOC_DATA') : bool(false)
I ended up creating a new method hasRole
in my User
Class :
public function hasRole($role)
{
return in_array($role, $this->getRoles());
}
Then, in a template, I use:
{% if app.user.hasRole('ROLE_VIEW_GEOLOC_DATA') %}
{# do something #}
{% endif %}
EDIT:
As @JonnyS said, it may be possible that roles must start with ROLE_
to work with is_granted
Symfony's function. Didn't tested.