How to Create a Quick Drupal Module

This tutorial will demonstrate how to create a Drupal Block Module. We will discuss converting a Twitter Widget into a configurable module as well as discuss some basic development techniques in Drupal Module development.

First and foremost, it is recommended that you have some knowledge of PHP and Drupal. If you are interested in creating more Drupal Modules, I implore you to check out the Drupal API and the Documentation pages. However, one thing I have noted is that WordPress and Drupal have a very similar way of handling things, which I will point out.

Setting up the Structure

We begin by creating an area for our module. If you are uploading directly to your Drupal installation, then create a folder called twitter_widget in the folder sites/all/modules/. However, if you do not have an accessible installation, then simply create the folder on your system. Within this folder we are going to create two files: twitter_widget.info and twitter_widget.module. Note that the name of the module will be the name used for functions and hooks in the Module file.

Adding Meta Information

In this step, we will add the meta information that Drupal will read to determine the compatibily and core information about the Module we are trying to work with. For this module, we will simply specify the required properties name, description and core. Although it’s optional to add the files property, it won’t hurt to do so. Copy the following snippet to your twitter_widget.info file.

name = Twitter Widget
description = Twitter Widget for Drupal
core = 7.x
files[] = twitter_widget.module

Declaring Block

Now, we’ll jump right into the twitter_widget.module file, and we’ll start by using the Drupal hook hook_block_info file. This hook defines all blocks provided by the module, and since our intention is to create just a block to hold our widget, it will be perfect. Starting with an opening PHP tag, copy the snippet to the file.

/**
 * Implements hook_block_info().
 */
function twitter_widget_block_info() {

$blocks['twitter_widget'] = array(
      'info' => t('Twitter Widget'),
    );

  return $blocks;
}

Take note that the that the word “hook” from hook_block_info is replaced with the name of the module twitter_widget. This how Drupal implements its hooks. Our hook has just the required value info. Depending on the nature of your block, you can add other values like cache, status, visibility and more.

Create Block Parameters

Just like the Joomla Module, we require adding some parameters to change the functionality of our Twitter Widget. The properties that we would like to control are the Twitter NameWidthHeight and No. of Tweets to display. In order to complete this parameter section, we use the hook hook_block_configure. We implement the hook by naming the function twitter_widget_block_configure.

This hook has a variable of $delta. Drupal states that “the $delta parameter tells the function which block is being requested” — and for this tutorial, we will only be using one block, so our $delta will be twitter_widget. Continue by adding the following snippet to your file.

/**
 * Implements hook_block_configure().
 *
 *
 */
function twitter_widget_block_configure($delta = '') {
  $form = array();
  if ($delta == 'twitter_widget') {
$form['twitter_widget'] = array(
  '#type' => 'fieldset',
  '#title' => t('Twitter Widget Options'),
);
    $form['twitter_widget']['twitter_widget_block_profile'] = array(
      '#type' => 'textfield',
      '#title' => t('Profile'),
      '#default_value' => variable_get('twitter_widget_block_profile', 'b4ucode'),
    );
    $form['twitter_widget']['twitter_widget_block_count'] = array(
      '#type' => 'textfield',
      '#title' => t('Tweets to Display'),
      '#default_value' => variable_get('twitter_widget_block_count', 3),
    );
    $form['twitter_widget']['twitter_widget_block_width'] = array(
      '#type' => 'textfield',
      '#title' => t('Width'),
      '#default_value' => variable_get('twitter_widget_block_width', 300),
    );
    $form['twitter_widget']['twitter_widget_block_height'] = array(
      '#type' => 'textfield',
      '#title' => t('Height'),
      '#default_value' => variable_get('twitter_widget_block_height', 300),
    );

  }
  return $form;
}

As you have seen, we defined a form array and in that array we create an array with a fieldset that will hold our other fields. Inside our arrays, we use type to define our form field, title for the name and default_value. For our Default Value, the function variable_get($name, $default = NULL) is called, which uses the parameters

  • $name: the name of the variable to return
  • $default: the default value to use if this variable has never been set

So what our function really says is: display a fieldset with the text fields of Profile, Tweets to Display, Width and Height.

Saving Parameters

Similar to the WordPress function add_option, we will save our module options using variable_set. This simple function uses an if statement to check the block we are looking at and then save each option defined for us.

/**
 * Implements hook_block_save().
 *
 *
 */
function twitter_widget_block_save($delta = '', $edit = array()) {
  if ($delta == 'twitter_widget') {
    variable_set('twitter_widget_block_count', $edit['twitter_widget_block_count']);
    variable_set('twitter_widget_block_profile', $edit['twitter_widget_block_profile']);
    variable_set('twitter_widget_block_width', $edit['twitter_widget_block_width']);
    variable_set('twitter_widget_block_height', $edit['twitter_widget_block_height']);
  }
}

Generating Content

Finally, we’ve arrived at hook_block_view. This will render our Block for us on the Drupal site. Inside this hook, we define our parameters as variables for ease of use. We get the parameters using the variable_get function which takes the function params of the value and a default value. Once the variables are defined, we’re going to grab the embed code from Twitter which we will be rendering on our site. The array key of subject is a default title for the block, while content will define the actual content that will be displayed on screen.

We’ll add our Twitter code to our array and replace the attributes with our parameter variables. Take note that we didn’t create a parameter for colors and background colors. Maybe you can make that your project!

 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function twitter_widget_block_view($delta = '') {
 $block = array();
  switch($delta) {
    case 'twitter_widget' :
      $block['subject'] = t('Twitter');

	//Assign Configuration to Variables
      $profile = variable_get('twitter_widget_block_profile', 'b4ucode');
      $width = variable_get('twitter_widget_block_width', 300);
      $height = variable_get('twitter_widget_block_height', 250);
      $count = variable_get('twitter_widget_block_count', 4);

	$html='';
	$html.='<script charset="utf-8" src="http://widgets.twimg.com/j/2/widget.js"></script>';
	$html.="
<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: ".$count.",
  interval: 30000,
  width: ".$width.",
  height: ".$height.",
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#000000',
      color: '#ffffff',
      links: '#4aed05'
    }
  },
  features: {
    scrollbar: false,
    loop: false,
    live: false,
    behavior: 'all'
  }
}).render().setUser('".$profile."').start();
</script>";
      $block['content'] = $html;
}
    return $block;
}

Testing the Module

If you have completed the tutorial thus far, you can test out your new Drupal Module. To test it out, make sure that it is found in the folder sites/all/modules/twitter_widget and enable it from the admin area. Tweak some parameters, save the block and see the magic unfold.

Conclusion

This tutorial is a good blueprint for creating even more Blocks — such as Facebook Like boxes, RSS Feed Widgets and so much more. Spread the word and share your thoughts. Happy Coding!

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • http://www.bluemwhitew.com Matt Walters

    Great tutorial, Kailan. :)

  • http://indiarto.net ari

    Clear explanation for me..

    Many thanks..

  • Anonymous

    Wow, sitepoint admitting drupal exists!

  • http://chamsocda.khonggianwebviet.com/ cham soc da

    good, i like it, thanks

  • http://findtoilet.dk/ Tine Müller

    Thanks Kailan for this great tutorial which I got to functioning on a Drupal 7 site http://myd7site.tinemuller.dk/node – But what if I want it on a Drupal 6 site? What to change then or maybe another module to use, please?