Monday, April 22, 2013

Drupal 7 Create a block that's only visible on specific pages programmatically.

A better view of this post can be viewed here on stackexchange

1) Create a new module or copy an existing one and rename it.

2) Enable PHP filter module ( included in core )

3) Create a block using the hook_block_info() hook.
For example:

 * Implements hook_block_info().
function mymodule_block_info(){
  $blocks['mymodule_block_name'] = array(
    'info' => t('Block description'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
    'region' => 'sidebar_first', // assign block region
    'status' => 1, // enable the block
    'visibility' => BLOCK_VISIBILITY_PHP, // set visibility to use the result of pages code
    'pages' => '',
  return $blocks;
TIP: create a block using the block UI after enabling the PHP filter module so you can test your 'pages' PHP code before putting it in the module and prevent having to disable, uninstall and enable your module every time you change your php code.

4) Create the content of the block using hook_block_view():

 * Implements hook_block_view
function vacancies_block_view($delta = '') {
  switch ($delta) {
    case 'mymodule_block_name':
      $block['subject'] = 'Block title';
      $block['content'] = 'Hello world!';  
  return $block; // dont forget to the return the $block!

5) upload your code and enable the module
Or if you used an existing module disable, uninstall, enable the module

6) clear cache and check the result