How to create a basic block code in the new Drupal 7 ...

Hi everyone!

As many will know, Drupal 7 comes with important changes, including the hooks. In the previous version of this powerful CMS to create a block from a custom module we had to use hook_block(), this function has been deprecated, and now is separated into eight different hooks:

 

In this post we will programming a basic block, so we only use hook_block_view() and hook_block_info() and the rest we can leave for another day...

Explaining a bit how it works...

In D6 we had to use a switch inside hook_block to know when it was making a request of type "info" and when one of a kind "view". In D7 we have a hook for each of these requests so that our code can be more clear and legible.

 

We see the example

example.info

; $Id: example.info,v 1.0.0.0 2011/02/09 10:11:15 MyName Exp $
name = "Example Block"
description = "Example Block In Code"
core = "7.x"
package = "Custom Modules"

example.module

// $Id: example.module Exp $

/**
 * Implementation of hook_block_info().
 */
function example_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('Block Name'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function example_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      $block['subject'] = t('Block Name');
      $block['content'] = example_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function example_contents() {
  return '
    </p><div class="body">
      Hello World, this is a example custom Block
    </div><p>
  ';
}

 

As you can see is very easy to apply and more understandable than before...

Until next post!

Author

PHP Developer
PHP Developer. Currently working on projects based on Drupal Framework.

Comments

yesssssssssssssssss. that is super

This code helped a lot. Thank you for providing this (:

How can a custom tpl.php file be used?

thanks for tutorial