1

I have created a custom block of id downloadourapp and I would like to show/hide it base on certain statements.

I have create my custom module along with .module file where the code should be, however, I failed to find the right function to be used for that matter.

is hook_block_view_alter is the right function and how to hide or show this downloadourapp specific block.

  • @NoSssweat the question does answer my question but for some reason it is not working for me, can you please check the updated section of my question ? – Vanessa Abi Rashed Jun 4 at 16:55
  • 1
    Needs to be return AccessResult::forbidden()->addCa.... – No Sssweat Jun 4 at 19:03
  • 1
    Also, you'll probably need to add a cache context of user agent, otherwise, it's probably going to cache the result of whatever the user agent happens to be on the first visit. – No Sssweat Jun 4 at 19:09
  • @NoSssweat return AccessResult::forbidden()->addCacheableDependency($block); worked for me but the problem lies under if ($block->getPluginId() == 'downloadourapp') { because when I remove this line, downloadourapp block is hidden for good along with all other blocks. Note: I am sure the block id is downloadourapp as taken from the block edit url /admin/structure/block/manage/downloadourapp but why it not being respected in code ? – Vanessa Abi Rashed Jun 4 at 19:24
  • 1
    Plugin ID doesn't equal Block ID, example. You can find the Plugin ID with Devel or alternatively change it to if ($block->id() = 'downloadourapp') { – No Sssweat Jun 4 at 19:47
1

Plugin ID doesn't equal Block ID, example.

isForbidden is not a static function, need to use forbidden.

if ($block->id() == 'downloadourapp') {

    // If the user's phone is Android.
    if(preg_match("/(android)/i", $_SERVER["HTTP_USER_AGENT"])) {

    return AccessResult::forbidden()->addCacheableDependency($block);

    }
}
| improve this answer | |
0

No, hook_block_view_alter() is not the hook you are looking for.

Try using hook_block_access() to control access to the block instead.

If you created your custom block programmatically, you can even control visibility directly from inside the block class via blockAccess().

| improve this answer | |

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