Community Documentation

Examples of Form Elements

Last updated August 10, 2011. Created by siruguri on February 26, 2009.
Edited by oranges13, noobee. Log in to edit this page.

Checkbox

<?php
$form
['copy'] = array(
 
'#type' => 'checkbox',
 
'#title' => t('Send me a copy.'),
);
?>

This will create one checkbox with a value of "Send me a copy." if it is checked with a label that says "Send me a copy." For more information see the Form API Reference for Checkbox Field

Checkboxes

<?php
$form
['options'] = array(
'#type' => 'checkboxes',
'#title' => t('Various Options by Checkbox'),
'#options' => array(
  
'key1' => t('Option One'),
  
'key2' => t('Option Two'),
  
'key3' => t('Option Three'),
),
'#default_value' => variable_get( 'options', array('key1', 'key3') ),
);
?>

This would create a checkbox group with 3 check boxes. Each one has a key formatted like "key#" which is the value passed when the box is checked. Each box has a label such as "Option One". The #default_value looks for the value of 'options' which is the name of this form field (see $form['options']). Using the array that is set in the default value, it will automatically check the boxes corresponding to the value of key1 and key3.

For all form fields that require options arrays, they can be formatted in one of two different ways:

// Safe key value and Human Readable Label
'#options' => array(
    'safekey' => t('Option One'),
    'safekey2' => t('Option Two'),
),

// Human Readable Label becomes Value
'#options' => array(
  t('Option One'),
  t('Option Two'),
),

If you plan on using a #default_value, its much easier to use the first option, so you have a key to feed into the default value array.

Textfield

<?php
$form
['sample_textfield'] = array(
 
'#size' => '20', // the visual width of the text box
 
'#weight' => '0', // Higher numbers will sink this field to the bottom of the form, lower numbers will float it to the top
 
'#field_suffix' => '</div>', // Code that will appear after the input field
 
'#field_prefix' => '<div class=\'sample_class\'>', // Code that will appear before the input field
 
'#type' => 'textfield', // The field type
 
'#title' => t('Sample textfield'), // Title label
 
'#default_value' => 'a sample value', // The text that will appear in the box by default
);
?>

More Information

Page status

Needs technical review

Log in to edit this page

About this page

Drupal version
Drupal 6.x
Audience
Programmers, Site administrators
Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.