Samuli Natri
Apr. 29, 2012
Updated: Nov. 22, 2016
13
By Samuli NatriApr. 29, 2012
(Updated: Nov. 22, 2016)
13

How to Create a Module #1 - Basics (Drupal 7 Tutorial) (Article)

In this tutorial we create a simple module.

Setup

  • Create a file sites/all/modules/own/custom/custom.info and write this in it:
name = Custom
description = Custom mdodule 
core = 7.x
package = Own
  • Create a file sites/all/modules/own/custom/custom.module and write opening php tag on the top

Don't start module name with a number and don't add ending php tag (?>)!

  • Enable the module in /#overlay=admin/modules


Commenting

It's a good practice to comment your modules so add this in you custom.module:

/**
 * @file
 * An example module for how to create a module tutorial.
 */
@file Means that this comment describes the whole file.

More about commenting conventions in here:

Doxygen and comment formatting conventions

Custom block

Now let's create a block so we can see what's happening with our module.

  • Write this function in your custom.module
/**
 * Implements hook_block_info.
 */
function custom_block_info() {
  $blocks['custom'] = array('info' => t('Custom block'));
  return $blocks;
}
hook_block_info() Tells Drupal that your module provides blocks.
$blocks['custom'] Drupal uses arrays extensively to store and pass information.
t() Translates your text to current/given language (also adds extra security).

block_info() is a hook. You can extend your module by implementing hooks. Hook is named like this: hook_block_info() and when you want to implement it replace the 'hook' with your module name: custom_block_info().

Another example of hook would be hook_node_insert. If your implement it with a function  custom_node_insert, that function will run everytime a node is created.

More hooks here:

http://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7

If you want to use variables, pass them with placeholders so they get sanitized . Like this:

global $user;
$account = $user;
$blocks['custom'] = array(
  'info' => t('Custom block for @user', array('@user' => $account->name)),
);

Now you can see the block in

/#overlay=admin/structure/block

  • Move it to Sidebar first and Save blocks.

Block content

Now let's create some content for our block.

  • Write this function in your custom.module
/**
 * Implements hook_block_view.
 */
function custom_block_view($delta = '') {
  global $user;
  $account = $user;
  $block['content'] = t('Hello @user from IP @host',array(
    '@user' => format_username($account), 
    '@host' => $account->hostname
  ));
  return $block;
}
hook_block_view() Returns a view for your block.
$delta Unique identifier for the block.
format_username() Function to format a username (returns Anonymous if there is no $user->name).

Now you should see something like this in your sidebar:

Retrieving data

To retrieve data from database, we use Drupal Database API. Let's fetch all node titles from node table:

/**
 * Implements hook_block_view.
 */
function custom_block_view($delta = '') {
  global $user;
  $account = $user;
  $block['content'] = t('Hello @user from IP @host',array(
    '@user' => format_username($user), 
    '@host' => $account->hostname
  ));
  
  $result = db_select('node','a')
    ->fields('a', array('title'))
    ->execute();
  
  foreach($result as $node) { 
    $items[] = array(
      'data' => t($node->title)
    );
  }
  
  $block['content'] .= theme('item_list', array(
    'items' => $items
  ));
  
  return $block;
}
db_select($table, $alias) Returns a SelectQuery object.
$table Target table for the query.
$alias Alias for the table.
fields() Fields to SELECT from $table
execute() Run the query.
theme() Creates themed output.

We iterate through the object with foreach and add titles to items[] array. Then we use theme() function to theme those titles to an item list and add that list to the block content.

Updating, Deleting and Inserting

Updating

You can update database items with db_update:

$update = db_update('node')
  ->fields(array(
    'title' => t('Updated by API')))
  ->condition('title','Test article 2','=')
  ->execute();

condition() Condition clause to restrict fetched rows by a condition. (Notice that the operator goes as last argument!)

Deleting

You can delete database items with db_delete

$delete = db_delete('node')
  ->condition('title','Test article','=')
  ->execute();

Inserting

You can insert database items with db_insert

$insert = db_insert('node')
  ->fields(array(
    'title' => t('Test article 3')))
  ->execute();



NOTE: These were examples how to directly interact with database through Drupal Database API, but if you want to load, update and save nodes programmatically, these would be better choices:

node_load()
node_save()
entity_load()
EntityFieldQuery

Comments

Good Explanition.

Hi, thanks so much for your nice tutorial,
It print just one node title, I dpm $items array it contains just one element, 
what is wrong in my code :

  function custom_block_view($delta='') {
      global $user;
      $account = $user;
      $block['content']=t('Hello @user from IP @host',array(
          '@user'=>format_username($user),
          '@host'=>$account->hostname
          ));
      $result = db_select('node','a')
              ->fields('a',array('title'))
              ->execute();
      foreach ($result as $node) {
          $items = array(
              t($node->title)
              ); 
      }
      $block['content'] .= theme('item_list',array(
          'items'=>$items
          )); 
      dpm($items);
      return $block;
  }

this line:

   foreach ($result as $node) {
          $items[] = array(
              t($node->title)
              ); 

I got it, thank you

 How can I pass multiple fields say nid and status using $data and render through $items?

foreach($result as $node) {
    $items[] = array(
      'data' => t($node->title)
    );
  }
 
  $block['content'] .= theme('item_list', array(
    'items' => $items
  ));

very informative and very good article.thanks for guidance !

Thanx a lot

This was extremely helpful. How do you output html? 

Hi! Use theme function. I actually use it in the section 5. Retrieving data:

  $block['content'] .= theme('item_list', array(
    'items' => $items
  ));

This prints out list elements.

Check more from here: https://api.drupal.org/api/drupal/modules!system!theme.api.php/group/the...
 

Its very useful for budding developers like me. Thanks a lot

Add new comment