Richard Parnaby-King
Richard Parnaby-King

Reputation: 14892

ZF2 ACL check link in view

I have set up my roles, resources and permissions in my bootstrap, and in my layout have set up a navigation menu based on this, and this works.

What I am attempting to do now is create an admin panel with edit / delete links IF the current logged in user has those permissions. e.g. I may have multiple roles that can view a list of cms pages, but only certain roles can edit a cms page, and only certain roles can delete a cms page.

At the moment I am just checking if the user is logged in:

<?php if($user = $this->identity()): ?>
    <?php if($user['role'] == 'admin'):?>
        <a href="/delete-url">Delete</a>
    <?php endif;?>
<?php endif;?>

How do I check the permissions of the current user role for the specified resource from the view for an arbitrary link (as above)?

Upvotes: 0

Views: 325

Answers (1)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14892

The ACL view helper is injected into the layout, so to check if a role has access to a resource, we can call $this->layout()->acl->isAllowed.

In this code snippet, we check if the user is logged in ($this->identity() returns false if not logged in, or an array of details if logged in), then if the user has 'delete' permission to the resource:

<?php if($user = $this->identity()); //is logged in? ?>
    <?php if($this->layout()->acl->isAllowed($user['role'], $resource, 'delete')):?>
        <a href="/delete-url">Delete</a>
    <?php endif;?>
<?php endif;?>

isAllowed signature is isAllowed($role = null, $resource = null, $privilege = null)

Upvotes: 2

Related Questions