Building your first Drupal 7 Module

Building your first Drupal 7 Module

Building your first module in Drupal 7 can be quite the task. You may find yourself in need of some custom functions to make your site work the way you want. Building a module is very similar to building a theme, and not much more difficult (provided you know some basic PHP). For this tutorial, we will build a module with an admin page that prints some text, a page with a form that stores new quiz titles to the database, and a page that displays a list of the quiz titles. The listing page will include some CSS and some jQuery just for fun (actually because you’ll probably use jQuery in a lot of your modules). We’ll call the module Quiz.

Before you start building your module, it is an important skill to understand how to document within your module. At some later date you might need to make some changes; without strong documentation notes, you will probably have to read through every line of code to find where to make the changes. If you document as you go along, it will be easy to quickly find functions to change. If you plan to share your module with others, they will also greatly appreciate properly documented work, or they might find a bug they could easily fix for you. Without notes, they will likely give up on the code.

First, you will need to create some basic files to start: quiz.info, quiz.install, and quiz.module. The .info and the .module files are required to build any module. The .info file contains the basic data Drupal uses to work with the module. Drupal requires the .install file for adding database tables to the system, so we need that to store our quizzes. The .module file is a PHP file, which can contain all of the PHP code used by the module. As a module developer, you’ll find it easier to split up the PHP into separate files for easier understanding and debugging later on. In the case of this module, I didn’t split the coding because there are so few lines. Additionally, you may want to include a .js file, which would contain javascript and jQuery, or a .css file, which would contain any CSS. And finally you may want to use .inc files to contain some extra PHP functions (this is where you’d split off some of the functions for organization).

The entire module is available for download so you can use it to build your first module by clicking here. It may also be helpful in some cases to further explain this documentation.

.info File

The quiz.info file is the trunk of the module tree. The file is a plain text document with information about the module. Some properties are required, and others are optional. The following are properties you are required to include so that Drupal can understand your module. Note: some of the lines are commented out because they are provided as examples.

 

; name of module
name = Quiz Module
; description of module
description = This module creates a quiz.
; fieldset grouping on module page
package = Quiz
; version of Drupal module runs on
core = 7.x
; Here are some optional properties you will typically add to your file.
; version of module (do not use on modules listed on the Drupal site)
version = 7.x-1.0
; link on module page to configuration page
configure = admin/config/system/quiz
; stylesheets added to module pages
stylesheets[all][] = quiz.css
; javascript files add to module pages
scripts[] = quiz.js
; other modules required to run module
; dependencies[] = views
; list of files with php classes (often used with views)
; files[] = quiz.extra.inc

 

You can learn more about each line, and lines I have not included, by visiting here. Some of the properties you may find you need to set after you have started writing your code for the module. For example, you may not have planned to include a configuration settings form with your module, but later you realize you need one. Or you may decide to add a stylesheet. In either case, simply edit the .info file and add the property. You may need to flush the Drupal cache to register the changes.

.install File

The .install file is used to add tables during install (and remove tables during uninstall) to the database using hook_schema. Drupal automatically adds and removes based on the schema. There is no need to use hook_install or hook_uninstall for this. Those two functions are for running other code during the install or uninstall, respectively. Often hook_uninstall is used to remove variables set by the module. The .install file should also contain any update functions (that will not be covered in this article).

The following shows you a bit of a schema. Most important in the hook are the fields. Without fields you will have no information in your table.

'fields' => array(
'qid' => array(
'description' => 'Quiz ID',
'type' => 'serial',
),
'name' => array(
'description' => 'Quiz title',
'type' => 'varchar',
'length' => 255,
'default' => '',
),
),

 

See the quiz.install file for a complete example. You can set up each table with fields, indexes, and keys. Visit here to learn more about the specifications of hook_schema.

.module File

The .module file can contain all of the necessary PHP to run a module (except install schemas). But as your modules get more complex you will find it helpful to organize the functions into categorized files. For example, you could place the configuration settings form, validation, and submission functions into a called quiz.admin.inc instead of leaving them in the .module file.

While writing code for Drupal you’ll create several types of functions, two of which are commonly used: functions for the module and HOOK_functions. The former are just as they sound, a function that you write for the use of the module. The latter can alter or add something often used in Drupal. One common example common hook is HOOK_form_alter(&$form, &$form_state), which allows you to change the form. Another example is the HOOK_menu() function. You replace HOOK with your module name, in this case quiz_menu. With this function you can create any type of menu item. Thousands of hooks exist, each one allowing you to tap into the power of Drupal.

Here is a single page set up with the hook_menu function.

 

// set path for menu item
$items['admin/config/system/quiz'] = array(
// title, automatically translated
'title' => 'Quiz info',
// function to return page as renderable array
'page callback' => 'quiz_admin_page',
// ‘access callback’ defaults to system permissions
// set like this
'access arguments' => array('administer site configuration'),
// normal menu item, defaults to Navigation menu
'type' => MENU_NORMAL_ITEM,
);

 

The page callback then will usually return a renderable array; in this case, we’ll do just that. Drupal will take the array and turn it into the main part of the page. Check out the example files to see the markup output.

Often you’ll be calling forms. They require a form function and a validate or submit function (you can save during the validation function or validate during the submit function, but neither is a good idea). A very simple form, with only a text field and submit button follows.

function quiz_form($form, &$form_state) {
$form = array();

// text field input
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
);
// submit button
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save quiz'),
);

return $form;
}

You call the function using the menu hook, with the following two lines.

'page callback' => 'drupal_get_form',
'page arguments' => array('quiz_form'),

In the module file you’ll find a validation and a submit function. This simple form will keep saving new titles into the database table. To edit with a form, you simply need to call up the old data and overwrite it, but that will not be covered in this article.

Displaying the Saved Data

What good is saving data into the database if you can’t also retrieve and display it? To display data, you must create a menu item and call the data from the database. Then you can transform that into a renderable array, which Drupal will turn into HTML.

Inside your page display function you can call drupal_add_css() and drupal_add_js() to add CSS and JS respectively. Either can load a file or insert inline code. Here is a simple call to each function to add CSS and JS to the page.

// add css inline
drupal_add_css('
#quiz-table tr.odd {
background:#333;
color:#fff;
}
', 'inline');
// add js inline
drupal_add_js("
(function ($) {
$(document).ready(function() {
$('#page-title').css('color', 'blue');
});
})(jQuery);
", 'inline');

In the example quiz display page, I’ve decided to display the quiz IDs and names in a table. Creating a table in Drupal 7 is as easy as inserting the header and rows into arrays and sending them to the theme function. To learn more about theming tables, visit here.

Review

This article has covered the very basics of creating your first Drupal 7 module. After following these instructions you should know how to create .info, .install, and .module files. You should also know how to create a menu item and a simple form, which stores data in the database. Lastly, you should be able to display that data on a page in HTML.