All the customizations in Drupal are done using hooks.
Hooks
Hooks are Drupal’s way of giving developers a chance (by calling hooks in their custom modules) to customize Drupal Core functionality and presentation. Read more about hooks here.
To manage a block’s visibility, Drupal has already set a few options. These include:
Visibility according to specific pages.
Visibility for different content types.
Visibility for different User roles.
Visibility for different Users.
We can find these options in the add-block form when we add a new block or edit an existing block. Now If we research on how Drupal really does it and where this functionality is coming from, We’ll end up at node module in Drupal Core for content type specific visibility and block module in Drupal Core for other options. The code would look somewhat like this:
hook_form_FORM_ID_alter() has been implemented in the above code which sets the various visibility settings for the add-block-form. The vertical tabs are represented by form elements which are fieldsets like:
To create our custom, our code should implement the same hook_form_FORM_ID_alter() and define a fieldset as:
We can also keep various elements inside our custom tab and use them to obtain values from users such as node types, date etc and customize the block visibility based on these values.
Let’s say we had to restrict the visibility of blocks before or after a certain date. To do this job we would need to ask users for the date. we can do that by simply defining a custom tab as above and asking users to enter the date in a text field and then use the date value to restrict the blocks’ visibility. Just like this:
The code for this would look somewhat like this:
I’ll soon be writing another blogpost to explain how to restrict a block’s visibility on a certain page. Stay tuned!