how do I let only certain users to view a block

how do I let only certain users to view a block

by Raphael Goldman -
Number of replies: 3

Hi,

I have created a block that is linking to a page that I created.

I want this block in the main site page and I need only some roles to be able to see that block.

I added the capability view to the block:

            'editingteacher' => CAP_ALLOW,

            'manager' => CAP_ALLOW

But actually everyone can see that block, 

How can I do it right?

Thanks

Average of ratings: -
In reply to Raphael Goldman

Re: how do I let only certain users to view a block

by Mary Cooch -
Picture of Documentation writers Picture of Moodle HQ Picture of Particularly helpful Moodlers Picture of Testers Picture of Translators

One way is documented in Blocks FAQ - see #4 , which mentions teachers but can be adapted for any role.

In reply to Raphael Goldman

Re: how do I let only certain users to view a block

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Do you mean that everyone can see the block, once it has been added, or that everyone has the ability to add the block?

The block/BLOCKNAME:addinstance capability controls who is allowed to add the block to a Moodle page.

There is no standard Moodle capability that will automatically control who will see a particular block once it has been created - you will have to write some code in your block to do this yourself.

Thankfully, it is really easy to do, just add the following to your block's 'get_content()' function:

if (!has_capability('block/BLOCKNAME:view', $this->context)) {
  return null;
}

(Note: this assumes that you replace 'BLOCKNAME' with the name of your block and that you have defined the block/BLOCKNAME:view capability in access.php and, if necessary, you have bumped up the version number to install this new capability).

Average of ratings:Useful (1)
In reply to Davo Smith

תשובה ל: Re: how do I let only certain users to view a block

by Raphael Goldman -

Thanks, that is what I was looking for.