Drupal custom module development tutorial

The module helps to extend and customize Drupal functionality. Drupal have three kinds of modules, core, contributed and custom. In this tutorial, you can learn how to create your own module in Drupal 7. Our step by step guide helps beginners to make a drupal 7 module from scratch. If you are new to Drupal, you can read Drupal 7 installation and setup tutorial for beginners first.
Let’s start the creation of your own Drupal module.

Step 1) Creating module folder and files

 Choose a short name for your module. Module name must start with a letter, and it must contain only lower-case letters and underscores. For this example, we’ll choose “latest_posts” as module name.

 Create a folder with module name (latest_posts) in sites/all/modules/ directory.

 Create a latest_posts.info file in the module directory (sites/all/modules/latest_posts/) for telling drupal about your module. latest_posts.info file contains the meta information of your module and it is required for your module. Missing of this file your module will not appear in the module listing.

sites/all/modules/latest_posts/latest_posts.info file contains the following code:

name = Latest Posts
description = A block module that lists links to newly created posts developed by CodexWorld.
core = 7.x

 Create a module file (latest_posts.module) into the module directory (sites/all/modules/latest_posts/).

  •  Module file has a name of the module directory name and an extension of .module.
  •  Module file is a PHP file and begins with opening PHP tag.
  •  Omit the closing (?>) tag for avoiding the runtime issues on the certain server.

For now sites/all/modules/latest_posts/latest_posts.module file contains the following code:

<?php

TEST
 Go to Modules listing page and scroll down of the list, you’ll see the Latest Posts module under the OTHER category.

latest-post-drupal-custom-module-in-list-by-codexworld

Step 2) Declaring the help hook

 Implement some hooks in latest_posts.module file. Also, it is a very good idea to document about how your module works in comments.

/**
 * @file
 * A block module that displays latest posts.
 */

 Implement a help hook (hook_help). This hook provides help and additional information about your module. Create a function called latest_posts_help() in latest_posts.module file and place the following code.

/**
 * Implements hook_help().
 *
 * Displays help and module information.
 */
function latest_posts_help($path$arg) {
    switch (
$path) {
        case 
"admin/help#latest_posts":
            return 
'<p>' t("Displays links to newly created posts developed by CodexWorld") . '</p>';
            break;
    }
}

TEST
 Go to the Modules listing page => Check the checkbox to enable your module => Click on Save configuration.

enable-drupal-custom-module-in-list-by-codexworld

 Help link would appear with your module. Help link will redirect you to the module help page.

drupal-custom-module-help-link-by-codexworld

 Return to the Modules listing page => Uncheck the checkbox to disable your module => Click on Save configuration.

Step 3) Declaring the block

 hook_block_info() is used to define a block. Create latest_posts_block_info() function in latest_posts.module file and place the following code.

/**
 * Implements hook_block_info().
 */
function latest_posts_block_info() {
    
$blocks['latest_posts'] = array(
        
// The name that will appear in the block list.
        
'info' => t('Latest posts'),
        
// Default setting.
        
'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return 
$blocks;
}

TEST
 Go to the Modules listing page => Check the checkbox to enable your module => Click on Save configuration.

 Navigate to the Structure » Blocks, scroll down to the bottom of the list. You’ll see your “Latest posts” block under the Disabled section.

drupal-custom-module-block-by-codexworld

 Return to the Modules listing page => Uncheck the checkbox to disable your module => Click on Save configuration.

Step 4) Retrieving data

 Now we’ll create a custom function to retrieve the newly created posts from the database. recent_posts_contents() function retrieved the post which are created within last week. recent_posts_contents() function would be the following.

/**
 * Custom content function. 
 * 
 * Set beginning and end dates, retrieve the recent posts from the database
 */
function recent_posts_contents(){
    
//Get today's date.
    
$today getdate();
    
//Calculate the date a week ago.
    
$start_time mktime(000,$today['mon'],($today['mday'] - 7), $today['year']);
    
//Get all posts from one week ago to the present.
    
$end_time time();
    
    
//Use Database API to retrieve recent posts.
    
$query db_select('node''n')
      ->
fields('n', array('nid''title''created'))
      ->
condition('status'1//Published.
      
->condition('created', array($start_time$end_time), 'BETWEEN')
      ->
orderBy('created''DESC'//Most recent first.
      
->execute();
    return 
$query;  
}

Step 5) Generating block content

 Using hook_block_view we’ll take the data generated by custom function (recent_posts_contents()) and turn into the block content. recent_posts_block_view() would be the following.

/**
 * Implements hook_block_view().
 * 
 * Prepares the contents of the block.
 */
function latest_posts_block_view($delta '') {
    switch (
$delta) {
        case 
'latest_posts':
            
$block['subject'] = t('Latest posts');
            if (
user_access('access content')) {
                
// Use our custom function to retrieve data.
                
$result recent_posts_contents();
                
// Array to contain items for the block to render.
                
$items = array();
                
// Iterate over the resultset and format as links.
                
foreach ($result as $node) {
                  
$items[] = array(
                    
'data' => l($node->title'node/' $node->nid),
                  ); 
                }
                
// No content in the last week.
                
if (empty($items)) {
                    
$block['content'] = t('No posts available.');  
                } 
                else {
                    
// Pass data through theme function.
                    
$block['content'] = theme('item_list', array(
                      
'items' => $items));
                }
          }
        return 
$block;
    }
}

TEST

 Go to the Modules listing page => Check the checkbox to enable your module => Click on Save configuration.

 Navigate to the Structure » Blocks and scroll down to the bottom of the list. From Disabled section set your “Latest posts” block location to the page region and click on Save blocks.

 If you choose the “Sidebar first” region for “Latest posts” block, you’ll see the latest posts list at the left sidebar.

drupal-custom-module-block-view-by-codexworld

 Congratulation! You have successfully created the basic Drupal custom module.

Advanced feature:

Now we’ll implement some advanced feature and make the custom module more flexible. We’ll create a configuration form where admin would be able to adjust the number of links to display.

Step 6) Preparing for a module configuration form

 Using hook_menu(), we’ll define our form. Define latest_posts_menu() function in latest_posts.module file and add the following code.

/**
 * Implements hook_menu().
 */
function latest_posts_menu() {
    
$items = array();
  
    
$items['admin/config/content/latest_posts'] = array(
      
'title' => 'Latest posts',
      
'description' => 'Configuration for Latest posts module',
      
'page callback' => 'drupal_get_form',
      
'page arguments' => array('latest_posts_form'),
      
'access arguments' => array('access administration pages'),
      
'type' => MENU_NORMAL_ITEM,
    );
  
    return 
$items;
}

title: Required. The title of the menu item.
description: The description of the menu item.
page callback: The function to call to display a web page when the user visits the path.
page arguments: An array of arguments to pass to the page callback function.
access arguments: An array of arguments to pass to the access callback function.
type: Types constant are MENU_NORMAL_ITEM, MENU_CALLBACK, MENU_SUGGESTED_ITEM, MENU_LOCAL_ACTION, MENU_LOCAL_TASK, MENU_DEFAULT_LOCAL_TASK.

 Add the configuration button in Modules list by adding the following line in latest_posts.info file.

; NEW LINE	
configure = admin/config/content/latest_posts

Step 7) Declaring the form

 As per the “page callback”, drupal_get_form is called when the link is requested and “page arguments” values are passed to that function. By assigning latest_posts_form, we define that as both the form ID and the name of the function that will create our configuration form.
Create a function called latest_posts_form() and build a form by adding elements to $form array. Add the following code to latest_posts.module file.

/**
 * Page callback: Latest posts settings
 *
 * @see latest_posts_form()
 */
function latest_posts_form($form, &$form_state) {
    
$form['latest_posts_limit'] = array(
      
'#type' => 'textfield',
      
'#title' => t('Maximum number of posts'),
      
'#default_value' => variable_get('latest_posts_limit'3),
      
'#size' => 2,
      
'#maxlength' => 2,
      
'#description' => t('The maximum number of links to display in the block.'),
      
'#required' => TRUE,
    );
  
    return 
system_settings_form($form);
}

Step 8) Modifying the query

 You should need to modify the recent_posts_contents() function. Retrieved the data from the module settings form using variable_get() and add the limit to the database query. Modified recent_posts_contents() function would be look like the below.

/**
 * Custom content function. 
 * 
 * Set beginning and end dates, retrieve the recent posts from the database
 */
function recent_posts_contents(){
    
//Get today's date.
    
$today getdate();
    
//Calculate the date a week ago.
    
$start_time mktime(000,$today['mon'],($today['mday'] - 7), $today['year']);
    
//Get all posts from one week ago to the present.
    
$end_time time();
    
    
//NEW LINE 
    
$limit variable_get('latest_posts_limit'3);
    
    
//Use Database API to retrieve recent posts.
    
$query db_select('node''n')
      ->
fields('n', array('nid''title''created'))
      ->
condition('status'1//Published.
      
->condition('created', array($start_time$end_time), 'BETWEEN')
      ->
orderBy('created''DESC'//Most recent first.
      
->range(0$limit//NEW LINE
      
->execute();
    return 
$query;  
}

TEST

 Go to Configuration » Performance, and click the Clear all caches button.

 Go to the Modules listing page => Check the checkbox to enable your module => Click on Save configuration. You’ll see the Configure link along with the module.

drupal-custom-module-configure-link-by-codexworld

 Click on the Configure link, you would be redirected to the module settings page. You can set the maximum number of the posts to be displayed in the block.

drupal-custom-module-settings-form-by-codexworld

Based on this tutorial we have created a Drupal custom module named latest_posts. You can download this module from the below Download Source Code link.

 Well done! You have been developed your own module in Drupal 7. We have completed the Drupal module creation tutorial and if you have any query about Drupal custom module development, don’t hesitate to comment here.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up