Django - The Easy Way Django - The Easy Way
Samuli Natri 2012.04.26
Samuli Natri has been a software developer since the 90's. He enjoys building web applications and games. He attended Helsinki University Of Technology (Computer Science) and Helsinki University (Social Sciences).

Drupal 7 - How To Create A Custom Form

Tutorial on how to create a custom form.

The HTML way

In you want to create a two field form in HTML, you would write something like this:

<form id="test-form" method="post" action="/formtest">
  <label for="firstname">Firstname </label>
  <input id="firstname" type="text" name="firstname">
  <label for="lastname">Lastname </label>
  <input id="lastname" type="text" name="lastname">
  <input id="submit" type="submit" value="Submit">

The Drupal way

In Drupal we create similar form like this:

Create a custom module

Create a file sites/all/modules/own/form_test/form_test.info with this in it:

name = form_test
description = form_test
core = 7.x
package = Own

Create a file sites/all/modules/own/form_test/form_test.module

Note: Start it with <?php tag, but don't add ending ?> tag.

Write these functions in your module:

function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
  return $items;
Name Description
form_test_menu Creates a menu item in the navigation menu so we can have a place where to show our custom form. You can think that menu address referring to a page yoursite/formtest.
title Title of the page.
page callback Calls a function drupal_get_form which returns a render array for drupal_render().
page arguments Here we pass our custom render array (which form_test_form returns) as an argument for drupal_get_form.
access callback Allow unrestricted access.

Rendering means turning a structured array into HTML.

function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
  return $form;

When you use a function to return a render array for drupal_get_form, there are two default parameters that are in use:

Name Description
$form Holds the form array items we define inside the function when this function is called again.
&$form_submit Holds various data items like the values you pass when you submit the form.

Ampersand & means that this is a reference to a variable, so if we change this variable in this function, changes will show in the parent function too.

Form items are added as arrays to the $form variable. Hash (#) sign refers to an attribute of the item.

Enable the module in admin/modules. Flush caches.

Form can be seen in yoursite/formtest, but it doesn't do anything yet.