Creating blocks in your drupal module

In Drupal 7, there are a few hooks you have to implement in order for your module to add a block.

Required Block Hooks

hook_block_info()

hook_block_info() registers your block.

<?php

/**
 * Implements hook_block_info().
 */
function bab5_guide_block_info() {
  $blocks = array();

  $blocks['bab5_episode_assessments'] = array(
    'info' => t('Babylon 5 Episode Assessments'),
  );

  return $blocks;
}

hook_block_view()

Hook_block_view registers the callback that generates the block content.


<?php /** * Implements hook_block_view(). */ function bab5_guide_code_block_view($delta = '') { if($delta == 'bab5_episodes_assessment') { return array( // The block's title 'subject' => t('Babylon 5 Episode Assessments'), // the block's content 'content' => bab5_guide_assesment_block_generate(), ); } }

hook_block_generate()

hook_block_generate() generates the block content.


<?php /** * Generates Assessments Block content. */ function bab5_guide_assessments_block_generate() { global $user; $query = new EntityFieldQuery(); $result = $query->entityCondition('entity_type','node') ->entityCondition('bundle','episode_assessment') ->fieldCondition('field_author_id','uid',$user->uid) ->execute(); if($result) { $nids = array_keys($result['node']); if($nids) { $nodes = node_load_multiple($nids); $output = "<table>"; $output .= "<tr><th>Score</td><th>Date</td></tr>"; foreach ($nodes as $n) { $output .="<tr>"; $output .= "<td>" . $n->field_assessment_score['und'][0]['value'] . "</td>"; $date_str = $n->field_assessment_date['und'][0]['value']; $output .= "<td>$date_str</td>"; $output .="</tr>\n"; } $output .="</table>"; return $output; } } return "<p>No Assessments yet!<p>"; }

Category:

Add new comment

Filtered HTML

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

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.