How to Create a Drupal 6 Module
A basic Drupal 6 module requires three things:
- A folder with the module's name to contain the files,
- An info file that describes the module, and
- A module file that contains the php code.
As an example, I'll create a module to remove unwanted fields in the blog entry form. To begin with, I create a folder entitled fieldremover and then add two blank files to it, entitled fieldremover.info and fieldremover.module. Next, I open up the file: fieldremover.info with my text editor and fill it with:
name = Blog Field Remover
description = Removes unneeded fields from the blog entry form
version = "6.x-1.x"
core = "6.x"
project = "fieldremover"At this point, I could turn this module on in Drupal, though it wouldn't actually do anything. To add the functionality, I open up fieldremover.module and fill it with:
<?php
// $Id: fieldremover.module,v 1.0 $
/*
* @file
* Drupal Module: fieldremover
* Removes unneeded fields from the blog entry form.
*/
function fieldremover_form_alter(&$form, &$form_state, $form_id) {
// print $form_id;
switch ($form_id) {
case 'blog_node_form':
// remove some unwanted node editing fields
$form['revision_information']['#access'] = 0;
$form['menu']['#access'] = 0;
$form['author']['#access'] = 0;
// override node permissions defined by 'administer nodes'
$form['options']['#access'] = 1;
$form['options']['status']['#access'] = 1;
$form['options']['promote']['#access'] = 0;
$form['options']['sticky']['#access'] = 0;
break;
}
}
?>The comments at the beginning are consistent with Drupal coding standards.
This module makes use of the hook_form_alter Drupal function. To use it, you simply create a function called [modulename]_form_alter, using the parameters shown. For all the hook functions available, check out the Drupal hooks API.
To figure out which form I'm altering, I can uncomment the print $form_id line, and the form names will appear at the top of your page. (Remove this line in production environments, of course!)
Notice that we're mostly just ripping out sections of the form. Removing the author section does not work well, however, because it makes all nodes authored by the anonymous user. By disabling the author section of the form, I'm removing the ability to override authorship information even for users who would normally be allowed to do so, like the site administrator.
That's all there is to it, but you may be wondering how I know what values to manipulate. Add the following section of code after (or replacing) the unset commands:
<?php
$form['form_array'] = array(
'#value' => '<pre>'. print_r($form, 1) .'</pre>',
'#weight' => '99',
);
?>This piece of code adds a new element, called form_array to the form. It will spit out a big ugly hunk of preformatted text at the end of your node edit form, showing all of the existing form elements, any of which can be altered.
- Adrian Hirt's blog
- Login to post comments