-1

What I really want is that I have a block and I want it to be shown only for authenticated users.

Can anyone help me?

Note: I want to do it programmatically without an extra module.

2
  • admin is also authenticated, is that what you want? Oct 1, 2015 at 12:31
  • 1
    Possible duplicate of drupal.stackexchange.com/questions/69861/… (assigning access to the "authenticated user" role in your case). BTW, it would be useful to edit the original question to mention that you want to do it programmatically ;)
    – dinopmi
    Oct 1, 2015 at 12:52

4 Answers 4

1

hook_block_list_alter()

global $user;

check $user->roles and unset your block:

function modulename_block_list_alter(&$blocks){
  global $user;
  $roles = $user->roles;
  if(!in_array('authenticated user', $roles)){
    unset($blocks[6]); 
  }
  // 6 is actually a block id witch is 
  //an array key from $blocks
}

I have just tested it with simpletest and it works. You need to check the user roles also.

8
  • could you help me how to unset a block?
    – Karmen
    Oct 1, 2015 at 12:54
  • global $user; if (!isset($user->uid)) { unset($blocks[19]); } this does not work for me
    – Karmen
    Oct 1, 2015 at 13:19
  • $user->id is allway set. like $user->id = 0 for anonymous Oct 1, 2015 at 13:21
  • global $user; if ($user->uid = 0) { unset($blocks[19]); } It also does not work again...
    – Karmen
    Oct 1, 2015 at 13:37
  • with $user->uid = 0 you just assignet 0 to $user->uid. Replace it with $user->uid == 0 or even better take a look on my last edit;) Oct 1, 2015 at 13:38
2

Check out this module block access

0
2

there is the option of assigning a role in the block settings under the Visibility settings.

5
  • use php code for the body section and put the condition if($user == admin) { // body content } the body content only show if user admin. Oct 1, 2015 at 12:40
  • as body content what do you mean?
    – Karmen
    Oct 1, 2015 at 12:40
  • if you add block then you write your code under "Block body". Oct 1, 2015 at 12:43
  • Is the main-menu block from admin_menu module
    – Karmen
    Oct 1, 2015 at 12:44
  • can you explain what actually you want. Oct 1, 2015 at 12:55
1

If you looking it through grammatically so follow this.

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

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

    case 'demo_block2':
      if ($user->uid) {
        $block['content'] = t('Hello Authenticated User');
      }
      break;
  }

  return $block;
}

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.