Drupal - Easy way to create blocks programmatically?

For Drupal 7:

Use hook_block_info and hook_block_view hooks in your custom module. hook_block_info defines the block. It will show up in admin > structure > blocks. *hook_block_view* displays the content. See examples below from the Drupal API.

Example of hook_block_info, where two blocks are defined (titled Syndicate and Recent content):

    <?php
function hook_block_info() {
  // This example comes from node.module.
  $blocks['syndicate'] = array(
    'info' => t('Syndicate'), 
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['recent'] = array(
    'info' => t('Recent content'),
    // DRUPAL_CACHE_PER_ROLE will be assumed.
  );

  return $blocks;
}
?>

Example of hook_block_view:

<?php
function hook_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {
    case 'syndicate':
      $block['subject'] = t('Syndicate');
      $block['content'] = array(
        '#theme' => 'feed_icon', 
        '#url' => 'rss.xml', 
        '#title' => t('Syndicate'),
      );
      break;

    case 'recent':
      if (user_access('access content')) {
        $block['subject'] = t('Recent content');
        if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
          $block['content'] = array(
            '#theme' => 'node_recent_block', 
            '#nodes' => $nodes,
          );
        }
        else {
          $block['content'] = t('No content available.');
        }
      }
      break;
  }
  return $block;
}
?>

Refer to the Blocks API page on Drupal.org for full list of hooks. Drupal 6 is a little different. There is no hook_block_view hook; instead use hook_block to declare blocks.


For Drupal 6, the short answer is that you create a custom module that implements hook_block.

For Drupal 7, you use the Block API.

If this is your first foray into module development, I highly recommend Pro Drupal Development or Pro Drupal 7 Development. Pretty much everything you need to know is in there.


You might be looking for what I was looking for and found it here:

/modules/block/block.module:
block_custom_block_save($edit, $delta).

But when you look at this function you'll see that you can just do the db_update yourself.

db_update('block_custom')
->fields(array(
  'body' => $edit['body']['value'],
  'info' => $edit['info'],
  'format' => $edit['body']['format'],
))
->condition('bid', $delta)
->execute();

Tags:

Blocks