The HTML way

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

1
2
3
4
5
6
7
<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">
</form>

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:

1
2
3
4
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:

1
2
3
4
5
6
7
8
9
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;
}
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

$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.