9

In my template, I need to know if a user has certain role to display things according to it. So far, I've implemented a little function in my user class:

  public function hasRole($role) {
    $roles = array();
    foreach ($this->getRoles() as $rol) {
      $roles[] = $rol->getRole();
    }
    return in_array($role, $roles);
  }

which tells me if this user has the role specified by the string passed as a parameter. This work and can be called from a twig template, but doesn't allow me to know anything about the roles hierarchy. Is there a way to access the role hierarchy from a controller? and directly from a twig template? I've looked through the official docs and didn't find anything about.

hakre
  • 193,403
  • 52
  • 435
  • 836
Throoze
  • 3,988
  • 8
  • 45
  • 67

1 Answers1

21

You can check the roles in twig templete by using below code,It explains that if the current user has the below role,then show something

{% if is_granted('ROLE_ADMIN') %}

  //show things related to admin role

{%else if is_granted('ROLE_USER')%}
//show things related to user role
{% endif %}

Hope this helps you. Happy Coding!!

Asish AP
  • 4,421
  • 2
  • 28
  • 50
  • Thanks for your answer! One question: What if my user has the `ROLE_SUPERADMIN` which is hierarchically greater than `ROLE_ADMIN`? does `{% if is_granted('ROLE_ADMIN') %}` evaluate `true`? – Throoze Apr 22 '12 at 04:50
  • 1
    Throoze@: if a user logged in with ROLE_SUPERADMIN ,he is hierarchically greater than ROLE_ADMIN(hope hierarchical order you specified in secutiy.yml),then it will evaluate true,because hierarchically he is a user with both ROLE_SUPERADMIN and ROLE_ADMIN so it becomes True – Asish AP Apr 22 '12 at 07:37
  • sorry for bothering you... which is the equivalent to `is_granted()` in a controller? – Throoze Apr 22 '12 at 13:06
  • 4
    Throoze@: in controller you can check the users in role wise as below code if(TRUE === $this->get('security.context')->isGranted('ROLE_SUPERADMIN')){//superADMIN} else if(TRUE === $this->get('security.context')->isGranted('ROLE_ADMIN')){//ADMIN} – Asish AP Apr 23 '12 at 04:07