WDTUTORIALS

Drupal 7 - How To Create A Simple Module

Tutorial on how to start module development.

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 custom.module:

<?php
/**
 * @file
 * A simple module.
 */
Name Description
@file Means that this comment describes the whole file.

More about commenting conventions in here: API documentation and comment standards

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;
}
Name Description
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 and adds extra security.

block_info() is a hook. You can extend your module by implementing hooks. Read more: 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;
}
Name Description
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;
}
Name Description
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. HTML list in this case.

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.

Update, Delete and Insert

Update

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();

Name Description
condition() This clause is used to restrict fetched rows by a condition. (Notice that the operator goes as last argument!)

Delete

You can delete database items with db_delete:

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

Insert

You can insert database items with db_insert:

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

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 might be better: node_load(), node_save(), entity_load(), EntityFieldQuery.

Samuli Natri (Entrepreneur, WDTutorials.com founder) has been building websites since the late 90's. He attended Helsinki University Of Technology (Computer Science) and Helsinki University (Social Sciences).

Latest Tutorial CKEditor Tutorial With CodeSnippet Syntax Highlighting

Copyright @ 2018 WDTutorials.com. All rights reserved. Privacy policy.Terms Of Service.