Creating custom module in Drupal 7

May 25, 2017
admin
Telling Drupal about your module:

Main topic described: .info files

All modules must have a ‘modulename.info’ file, which contains meta information about the module.

The general format is:

name = Module Name 
description = A description of what your module does. 
core = 7.x

For our module, we will replace ‘Module Name’ in the example above with the name of our module, ‘Current Posts’. Without this file, the module will not show up in the module listing. Here is our specific example:

name = Current Posts 
description = A block module that lists links to recent posts. 
core = 7.x 
package = My Modules

Add the source above to a file named current_posts.info and save it into the module’s directory at sites/all/modules/current_posts.

Drupal uses .info files to store metadata about themes and modules.

For modules, the .info file is used for:

  • rendering information on the Drupal Web GUI administration pages;
  • providing criteria to control module activation and deactivation;
  • notifying Drupal about the existence of a module;
  • specifying the module’s dependencies on other Drupal projects
  • general administrative purposes in other contexts.

This .info file is required for the system to recognize the presence of a module.

The Drupal 7 Hook Concept:

Drupal’s hook system allows modules to interact with and alter data of other modules (or even Drupal core itself.)

Creating a Drupal 7 hook (and calling their implementations)

Creating a hook and calling their implementations can be done by using one of the following functions (not all included): drupal_alter(), module_invoke_all() and module_invoke()

Implementing a Drupal 7 hook

To be able to call it you need to implement a drupal 7 hook.If the module file is called example.module, then hook_help() as implemented by that module would be defined

If the module file is called example.module, then hook_help() as implemented by that module would be defined as example_help().

Drupal 7 Hook Types:

In common practice, there are two types of hooks that you want to create:

In common practice, there are two types of hooks that you want to create:

  1. Alter hooks: a common way to edit the contents of a particular object or variable by getting variables in the hook by reference, typically by using drupal_alter()
  2. Intercepting hooks: allowing external modules to perform actions during the execution, can not get variables by reference, typically by using module_invoke_all() and module_invoke()
Implementing your first hook

Hooks are fundamental to Drupal modules. They allow you to integrate your module into the actions of Drupal core. If you missed it, go back and read about hooks in Introduction to Drupal modules. Drupal’s API documentation provides a list of available module hooks.

Your first hook is hook_help. This hook is recommended for inclusion in all contrib modules. hook_help provides help and additional information about the module to the user. To implement any hook in Drupal, replace “hook” in the hook name with your module’s short name, and create a function in the .module file with that name. So, to implement hook_help() in our example module, we create a function called current_posts_help() in the current_posts.module file:

function current_posts_help($path, $arg) {

}
Writing .install Files (Drupal 7.x):

Drupal 7 uses .install files to create database tables and fields, and to insert data. Drupal 7 .install files can also provide updates to change the database structure and content. Drupal 7 also uses .install files and includes the Field module in core. Field provides a different way to send data to nodes than in Drupal 6 and could replace some .install files.

.install file

In Drupal 7, .install files can define new tables, load data, and implement conversions during updates.

A .install file is run the first time a module is enabled, and is used to run setup procedures as required by the module. The most common task is creating database tables and fields. The .install file does not have any special syntax. It is merely a PHP file with a different extension.

.install files are also used to perform updates when a new version of a module needs it.

Instructions

Install instructions are enclosed in a _install() function. This hook will be called when the module is first enabled. Any number of functions can reside here, but the most typical use is to create the necessary tables for your module.

Database tables are created using the Schema API.

The Schema API allows modules to declare their database tables in a structured array (similar to the Form API) and provides API functions for creating, dropping, and changing tables, columns, keys, and indexes.

A sample schema data structure (taken from the Schema Api Documentation)

As an example, here is an excerpt of the schema definition for Drupal’s ‘node’ table:

$schema['node'] = array(
'description' => 'The base table for nodes.',
'fields' => array(
'nid' => array(
'description' => 'The primary identifier for a node.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE),
'vid' => array(
'description' => 'The current {node_revisions}.vid version identifier.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0),
'type' => array(
'description' => 'The {node_type} of this node.',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => ''),
'title' => array(
'description' => 'The title of this node, always treated a non-markup plain text.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => ''),
),
'indexes' => array(
'node_changed' => array('changed'),
'node_created' => array('created'),
),
'unique keys' => array(
'nid_vid' => array('nid', 'vid'),
'vid' => array('vid')
),
'primary key' => array('nid'),
);

In this excerpt, the table ‘node’ has four fields (table columns) named ‘nid’, ‘vid’, ‘type’, and ‘title’. Each field specifies its type (‘serial’, ‘int’, or ‘varchar’ in this example) and some additional optional parameters, including a description.The table’s primary key is the single field ‘nid’. There are two unique keys: first named ‘vid’ on the field ‘vid’ and second called ‘nid_vid’ on fields ‘nid’ and ‘vid’. Two indexes, one named ‘node_changed’ on field ‘changed’ and one named ‘node_created’ on the field ‘created’.

The table’s primary key is the single field ‘nid’. There are two unique keys: first named ‘vid’ on the field ‘vid’ and second called ‘nid_vid’ on fields ‘nid’ and ‘vid’. Two indexes, one named ‘node_changed’ on field ‘changed’ and one named ‘node_created’ on the field ‘created’.

Creating tables: hook_schema and .install files

For the Schema API to manage a module’s tables, the module must have a .install file that implements hook_schema(). For example, mymodule’s mymodule.install file might contain:

function mymodule_schema() {
$schema['mytable1'] = array(
// specification for mytable1
);
$schema['mytable2'] = array(
// specification for mytable2
);
return $schema;
}

The tables declared by hook_schema() will be automatically created when the module is first enabled, and removed when the module is uninstalled. This happens before hook_install() is invoked, and after hook_uninstall() is invoked, respectively.

Declaring the Block:

To use this hook to define our block, go to your current_posts.module file and create the function current_posts_block_info() as follows:

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

Next we will create a custom function to retrieve the most recent posts. When a node is first created, the time of creation is stored in the database. We’ll use this database field to find our data.

We will call the function current_posts_contents. We continue to follow the naming convention by beginning with the module short name. Then we use a descriptive word that is not a Drupal hook. The function begins with getting the time numbers. Here’s the first part (without a closing brace because it’s not the complete function):

/**
* Custom content function.
*
* Set beginning and end dates, retrieve posts from database
* saved in that time period.
*
* @return
* A result set of the targeted posts.
*/
function current_posts_contents(){
//Get today's date.
$today = getdate();
//Calculate the date a week ago.
$start_time = mktime(0, 0, 0,$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 current 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;
}
Creating A Custom Form:

Following code will create a very basic form that only has one field, a submit button:<?php

<?php
function current_posts_form($form, &$form_state) {
$form['price'] = array(
'#type' => 'textfield', //you can find a list of available types in the form api
'#title' => 'What is Your Price?',
'#size' => 10,
'#maxlength' => 10,
'#required' => TRUE, //make this field required
);

$form['submit_button'] = array(
'#type' => 'submit',
'#value' => t('Click Here!'),
);

return $form;
}
?>

The process for creating a form is mainly two steps. The first is to build an associative array $form that contains all the fields. The second step is to return that $form variable.

To add a field, you set the variable $form[{name of your field}] = array(); Each field can then have a number of attributes, such as “#type” and “#value.” Most of these attributes are named with a preceding “#” sign.

The field we added above is a submit button with the text “Click Here!” on the button. Note that t() will output text and is a Drupal function that plays nice with translation.

Now that we have a form, we need to add two more function: current_posts_form_validate, and current_posts_form_submit. These two functions are hook functions that will be called when Drupal validates the form and when it submits the form (assuming it validated).

<?php
function current_posts_form($form, &$form_state) {
$form['price'] = array(
'#type' => 'textfield', //you can find a list of available types in the form api
'#title' => 'What is Your Price?',
'#size' => 10,
'#maxlength' => 10,
'#required' => TRUE, //make this field required
);

$form['submit_button'] = array(
'#type' => 'submit',
'#value' => t('Click Here!'),
);

return $form;
}

function current_posts_form_validate($form, &$form_state) {
}

function current_posts_form_submit($form, &$form_state) {
}
?>
Creating Custom Menu Link:

In drupal 7 we can create custom menus like this:

<?php

function current_posts_menu() {
$items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
'title' => 'Example Form', //page title
'description' => 'A form to mess around with.',
'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed. for a form, use drupal_get_form
'page arguments' => array('current_posts_form'), //put the name of the form here
'access callback' => TRUE
);

return $items;
}
?>

Now if we hit examples/form-example, then user will be redirected to the custom form page,[:]

Contributor:  Khalid MahmodNascenia

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.