Drupal7: How to build a simple drupal module

Introduction.

In this tutorial we create a simple druapl module that implements a custom block called “Top10” and that block become available for use on blocks page (?q=admin/structure/block). You can configure a theme to display this block in any of the theme’s regions, In this tutorial we configure the default theme “Bartik” to display this block in its region “Sidebar first”.

What is required ?

Basically you just need two files to implement a module.

1. ${module_name}.info 
2. ${module_name}.module

For registering this module with the drupal system you need to create a directory “${drupal_root}/ sites/all/modules/${module_name}” and copy the above two files in that directory. Lets' name this module as “helloblock” and implement the two required files.

helloblock.info  

<?php
name = helloblock
description = A simple helloblock module.
package = Core
version = VERSION
core = 7.x

; Information added by Drupal.org packaging script on 2015-10-21
version = "7.41"
project = "drupal"

helloblock.module  

<?php
//This has to return an array
function helloblock_block_info() {

$blocks['top10'] = array ( "info" => t('Top10'));

return $blocks;
}

function helloblock_block_view($delta=''){
$block['content'] = "";
switch($delta){
case 'top10':
$block['subject'] = t('Top 10');
$block['content'] = theme('top_10');
return $block;
}

}

function helloblock_theme() {
  return array(
    'top_10' => array(
      'variables' => array(),
    ),
  );
}

function theme_top_10($variables){
  $output = "<li> <a href="#">Top 10 Articles </a></li>";
  $output .= "<li><a href="#"> Top 10 Tips </a> </li>";
  $output .= "<li><a href="#"> Top 10 News </a> </li>";
  $output .= "<li><a href="#"> Top 10 Tools </a> </li>";
  return $output;
}

Enable the module

Once you copy the above two files in the target module directory, you should see the module appearing on modules page. Go and enable the module.

 

Enabling Drupal module

 

 

Map the block to the region

Once you enable the module, you should see the block appearing on blocks page, go and map the block to your preferred region. In this tutorial we are mapping it to the region “Sidebar first”.

 

Drupal Mapping block to a region

 

Final result.

Clear the cache and visit your home page, You should see the block appearing in the left side of the page as shown bellow.

drupal block