Programatic Block Creation in Drupal

To remove static blocks and replace with as custom block.

Implement hook_block specifying the default visibility and so on

<?php
$blocks
['random'] = array(
     
'info' => t('Random'),
     
'weight' => 0,
     
'status' => 1,
     
'region' => 'sidebar',
     
'pages'  => 'offers',
     
'visibility' => 0, // all pages except
     
'cache' => BLOCK_CACHE_PER_PAGE,
    );
?>

Create an update hook that deletes the old blocks and boxes (I've specified the ID as I know they won't change on my site).

<?php
function mymodule_update_6101(){
   
   
$items = array();
   
$items[] = update_sql('DELETE FROM {boxes} WHERE bid in (2, 12,13)');
   
$items[] = update_sql("DELETE FROM {blocks} WHERE module = 'block' AND delta in (2, 12, 13)");

// Update the 'blocks' DB table with the blocks currently exported by modules.
// It's a "private" function called when you visit
// the admin/build/block/list/ page
// calling it here causes the rehash which you otherwise have to visit the page to get
   
_block_rehash();

// clear the cache
   
cache_clear_all();
    return
$items;
}
?>

When you run update.php your shiny new blocks should then be immediately available with no manual steps required.

This makes it so much easier to test your upgrades.

Tags

Comments

_block_rehash()

There's an issue here

http://drupal.org/node/148531

Which discusses problems (and solutions) with using this function for contributed modules.

Post new comment

Got something to add - just enter a comment
all other fields are optional.

Your email address will not be published.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image without spaces, also respect upper and lower case.