I'm looking for the best way to programmatically hide a block. In Drupal 6 I'd normally use preprocess_block to do all my logic and then unset title and content/body from there. I've tried to do same thing in Drupal 7 but failed. What's the correct way of doing this? I'd like to avoid editing the settings through the UI as this change has to be deployed in code rather than database.
4 Answers
The best (IMHO) way is to implement hook_block_list_alter() in a custom module and unset specific blocks when you need to. Advantages are:
- No PHP code in your database, so your alterations can be managed in a version control system
- No hacking in the theme layer, so the alterations will remain when you switch themes
- Better performance because the block is removed from the list before it is rendered
Drupal core also uses this hook to hide blocks: block.module itself implements hook_block_list_alter to apply the default block visibility settings.
-
Would this effect visibility on the block listing page as well? I'd still need it available for when the client wants to edit the block. The block is visible to all users when a specific cookie is set.– digitalMay 15, 2012 at 12:36
-
No, the block admin page is built by invoking hook_block_info and hook_block_info_alter. May 15, 2012 at 13:10
Quickest way I could find was to use template_preprocess_page()
and unset the block from there. Not entirely sure it's the correct way but it works.
/**
* Implements template_preprocess_page().
*/
function MYTHEME_preprocess_page(&$variables) {
// If sub-menu block is available.
if (isset($variables['page']['sidebar_first']['menu_block_2'])) {
// Unset its placeholder block.
unset($variables['page']['sidebar_first']['block_3']);
}
}
-
1Yes, this worked for me to turn off modules using mobile_detect_variables.– MarkJan 11, 2016 at 23:55
In case someone else stumbles on this more than 1.5 years later, there is a module called Logic Block that allows you to handle exceptions such as these.
Logic block is a module designed to give site administrators extra control over how blocks are displayed - extending the default options for each block in some new ways.
Some things logic block can do
- Merge two blocks into one
- Prevent a block displaying if it contains certain words
- Show another block if one is empty
- Show a different block depending on a user's language
A default block is specified, and then its content is processed by this module in a one of four ways (although this module supports extending these).
Enable PHP filter module so that you can write PHP on block visibility settings page.
Like this
-
1I'd like to avoid editing the settings through the UI as this change has to be deployed in code rather than database.– digitalMay 15, 2012 at 8:31
-
1