20 Jun, 2009
Create a simple Drupal module with Form API, hook_validate and hook_submit
Posted by: zayn hamdan In: blog
Create a simple Drupal module with Form API, hook_validate and hook_submit
Drupal has many API we can play with. The most useful API is form API. I’ll show how to create a simple Drupal 5 module to add your friend data to database. Just create a MySQL table name “friends” with 3 field: ID, name, and email. Make sure the ID field is auto_increment.
Module can be created under directory: modules or sites/all/modules. I prefer to create new module on sites/all/modules, so our custom module is separated with core module. Create folder mymod on sites/all/modules then create file mymod.module and mymod.info
Write file mymod.info with this content:
name = My Module
description = My first time module
version = "1.0"
The .info file will appear on administration modules page. On this how to I will show you how to create module with hook_validate and hook_submit. You may say, hook is an function depends on what module you use. We create mymod module, so we will create mymod_{FUNCTION_NAME}_validate and mymod_{FUNCTION_NAME}_submit
Next fill the mymod.module with content as follows:
function mymod_add_friend () {
$form['name'] = array(
'#type' => 'textfield',
'#title' => 'Name',
'#size' => 30,
'#maxlength' => 128,
'#required' => TRUE
);
$form['email'] = array(
'#type' => 'textfield',
'#title' => 'Email',
'#size' => 30,
'#maxlength' => 128,
'#required' => TRUE
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
function mymod_add_friend_validate($form_id, $form_values) {
if (!empty($form_values['email']) && !valid_email_address ($form_values['email']))
form_set_error('', 'Your email is empty or not valid');
if (empty($form_values['name']))
form_set_error('', 'Your name is empty');
}
function mymod_add_friend_submit($form_id, $form_values) {
db_query ("INSERT INTO {friends} VALUES(0, '%s', '%s')", $form_values['name'], $form_values['email']);
drupal_set_message('Thank you. Your friend has added');
}
The first function builds a form with form API, you call this form by using drupal_get_form function, example:
print drupal_get_form('mymod_add_friend');
The second function check for form input, if the output return false then the form processing is halted and Drupal will show an error message
The third function execute the form submission if there are no errors or validation has passed, use drupal_set_message to display a success message.
Activate your module on administration page the place code print drupal_get_form(’mymod_add_friend’); on your template and you will get a form then congratulation, you have created a Drupal module succesfully!







