Adding fields to a form

Last modified: May 25, 2008 - 21:37

Adding a field to your form description function is very simple. All you need to do is define an element of your $form array, which in turn will be an array, and will describe the field you want to appear in your form. Example of a textfield:

<?php
$form
['example_textfield'] = array(
 
'#type' => 'textfield',
 
'#title' => t('Example Textfield'),
 
'#default_value' => 'some text',
);
?>

This defines an element of our form of type: 'textfield' and with a title and default value. The 'textfield' type is built in to Drupal, and will be rendered as a standard HTML textfield with an associated caption given by the #title attribute. You (or contrib modules) can provide definitions of custom form elements, that can then be used across forms in exactly the same way as above.

A reference of field types that are provided by Drupal core, can be found at: http://api.drupal.org/api/file/developer/topics/forms_api_reference.html

Note that the structured array returned by the form building function has some keys that start with # and some that don't. Those that do are attributes of those that don't, a common error is to forget to add the # to the start of an attribute name. FAPI will then try and interpret that attribute as a form element in its own right, and it gets very confused!

 
 

Drupal is a registered trademark of Dries Buytaert.