3

I have a module that has permission hook for normal access and for administrative access. I want to display two different blocks to different set of users. Say, the "admin" will only get to view one block and a "site owner" will see the other display.

So, till now what I have done is, declared 2 hook_block_info() as,

    $blocks = array();
//Block for the Normal Site Owners
$blocks['payouts'] = array(
    'info' => t('Listing of Payouts'),
    'cache' => DRUPAL_NO_CACHE,

);
//Block for the Administrators
$blocks['commission_payments'] = array(
    .....
            .....
);

When I declare the hook_block_view() I use user_access() to restrict the user's to see it. But is there any way I can restrict the user's to view the block infos in the region settings ? Is there any array parameter for hook_block_info that can achieve this? I suppose the 'page' parameter will only handle the page where to display the block.

3
  • Just a note that depending on your needs you may not need to write code to accomplish this. See randyfay.com/node/77, which has a Views-oriented approach pointers to other approaches.
    – rfay
    Commented Nov 7, 2011 at 15:23
  • Actually, I have some custom tables to work upon. So, I have to work in custom module. So, any other way outs ? Commented Nov 7, 2011 at 16:19
  • It's super easy to enable views for your custom tables. I'm not saying that's the most appropriate thing. But I'd provide views integration for any custom table that I ever wanted to view the data in.
    – rfay
    Commented Nov 8, 2011 at 16:48

2 Answers 2

1

An easy solution is just to check the user role in hook_block_view():

function hook_block_view($delta = '') {
  global $user;
  $block = array();

  switch ($delta) {
    case 'payouts':
      if (in_array('Admin', array_values($user->roles))) {
        $block['content'] = t('Hello Admin');
      }
      break;

    case 'commission_payments':
      if (in_array('Site Owner', array_values($user->roles))) {
        $block['content'] = t('Hello Site Owner');
      }
      break;
  }

  return $block;
}
0

Use the same trick that you do in block_view in your block_info. The array returned from block_info forms the list for the Block page. However, if a block has been enabled, it will no longer be visible, either in the Block page, or on your other pages (unless the user has permission).

hook_block_list_alter may also be an option for what you want, but is only D7 and up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.