Main navigation

How to Show or Hide Block Visibility in Drupal 8 Programmatically using PHP

ExamTray App is now Available on Google Play

How to Show or Hide Block Visibility in Drupal 8 Programmatically using PHP

Drupal 8 is made up of a number of Blocks. Each block represents one type of information. Also, each block has a place holder where it will be displayed. Some times it is necessary to show or hide blocks based on User Roles, specific path or pages. Visibility changes the way your Drupal Blocks appear to each user admin or anonymous.

Show or Hide Block in Drupal 8 Programmatically

You need a module to write code for restricting block access. So create a Drupal 8 Module with name mymodule.module. Inside the module, we are going to use hook_block_access function provided by drupal 8 to do customization. Now, we shall hide a block using PHP programmatically.

How to Find Block Name in Drupal 8

To find a block name, go to Structure and choose Block Layout. You can see a list of blocks from top to bottom. Against each block, there is a Configure Button.

Now click on Configure button. Just check the URL for block name of “Site Branding” for example.

In the code above, we are hiding the block mybootstrap_branding based on Node Type or Content Type or Path or User Role. You can add your own rules to suit your needs to change visibility of a Drupal 8 Block.

You can also restrict a node access in Drupal 8 based on various conditions like User Roles or Path. Drupal 8 has hooks for various purposes. We have to use those correctly.