A wrapper element to group one or more buttons in a form. Use of the 'actions' element as an array key helps to ensure proper styling in themes and to enable other modules to properly alter a form's actions.
This page provides a programmer's reference to the Backdrop CMS Form API. For a brief introduction on how to create forms, see the Form generation guide. For more extensive information about the Form API, see the Form API handbook (Drupal 7 documentation).
Skip to: Default Values | Elements | Properties
Simple Elements
Structural Elements
actions | ajax | container | details | fieldset | form | item | token | vertical_tabs | |
---|---|---|---|---|---|---|---|---|---|
#access | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#action | ✓ | ||||||||
#after_build | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#attached | ✓ | ||||||||
#attributes | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#children | ✓ | ✓ | ✓ | ||||||
#collapsed | ✓ | ||||||||
#collapsible | ✓ | ||||||||
#commands | ✓ | ||||||||
#config | ✓ | ||||||||
#default_tab | ✓ | ||||||||
#default_value | ✓ | ||||||||
#description | ✓ | ✓ | |||||||
#details | ✓ | ||||||||
#element_validate | ✓ | ✓ | ✓ | ✓ | |||||
#error | ✓ | ||||||||
#field_prefix | ✓ | ||||||||
#field_suffix | ✓ | ||||||||
#group | ✓ | ||||||||
#header | ✓ | ||||||||
#https | ✓ | ||||||||
#id | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#indentation | ✓ | ||||||||
#input | ✓ | ✓ | ✓ | ||||||
#markup | ✓ | ||||||||
#method | ✓ | ||||||||
#name | ✓ | ||||||||
#open | ✓ | ||||||||
#parents | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |||
#post_render | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#prefix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#pre_render | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#process | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#redirect | ✓ | ||||||||
#required | ✓ | ✓ | ✓ | ✓ | ✓ | ||||
#states | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#submit | ✓ | ||||||||
#suffix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#summary | ✓ | ||||||||
#theme | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#theme_wrappers | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
#title | ✓ | ✓ | |||||||
#title_display | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |||
#token_types | ✓ | ✓ | |||||||
#tree | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#type | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#validate | ✓ | ||||||||
#value | ✓ | ✓ | |||||||
#weight | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
#wrapper_attributes | ✓ |
Complex Elements
Renderable Elements (not limited to forms)
contextual_links | dropbutton | head_tag | help | link | markup | operations | scripts | styles | |
---|---|---|---|---|---|---|---|---|---|
#access | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
#after_build | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#aggregate_callback | ✓ | ✓ | |||||||
#ajax | ✓ | ||||||||
#attached | ✓ | ||||||||
#attributes | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ||
#disabled | ✓ | ✓ | |||||||
#element_validate | ✓ | ||||||||
#group_callback | ✓ | ✓ | |||||||
#id | ✓ | ✓ | ✓ | ✓ | ✓ | ||||
#input | ✓ | ✓ | ✓ | ✓ | |||||
#items | ✓ | ✓ | |||||||
#links | ✓ | ✓ | ✓ | ||||||
#markup | ✓ | ✓ | |||||||
#options | ✓ | ||||||||
#parents | ✓ | ✓ | ✓ | ✓ | |||||
#post_render | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#prefix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |||
#pre_render | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
#process | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
#required | ✓ | ✓ | ✓ | ✓ | |||||
#states | ✓ | ✓ | ✓ | ||||||
#suffix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |||
#tag | ✓ | ||||||||
#theme | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
#theme_wrappers | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
#title | ✓ | ||||||||
#title_display | ✓ | ✓ | ✓ | ✓ | |||||
#token_types | ✓ | ✓ | |||||||
#tree | ✓ | ✓ | ✓ | ✓ | |||||
#type | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |||
#value | ✓ | ✓ | |||||||
#weight | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
Elements
actions
<?php
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
$form['actions']['delete'] = array(
'#type' => 'button',
'#value' => t('Delete'),
);
$form['actions']['cancel'] = array(
'#markup' => l(t('Cancel'), 'foo/bar'),
);
?>
ajax
A form element that contains AJAX commands. See the AJAX Framework for details on usage.
<?php
function config_export_single_form_update_type($form, &$form_state) {
// Empty out the configuration value field.
$form['export']['#value'] = '';
$form['export']['#rows'] = 12;
// Because we need to replace both the configation name select and the
// textarea, this requires using AJAX commands instead of a simple return.
$commands = array();
$commands[] = ajax_command_replace('#edit-config-type-wrapper', backdrop_render($form['config_name']));
$commands[] = ajax_command_replace('#edit-export-wrapper', backdrop_render($form['export']));
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));
return array(
'#type' => 'ajax',
'#commands' => $commands,
);
}
?>
button
Format an action button. When the button is pressed, the form will be submitted to Backdrop, where it is validated and rebuilt. The submit handler is not invoked.
(node.module):
<?php
$form['preview'] = array(
'#type' => 'button',
'#value' => t('Preview'),
'#weight' => 19,
);
?>
checkbox
Format a checkbox.
<?php
$form['copy'] = array(
'#type' => 'checkbox',
'#title' => t('Send me a copy.'),
);
?>
checkboxes
Format a set of checkboxes. #options is an associative array, where the key is the #return_value of the checkbox and the value is displayed. The #options array cannot have a 0 key, as it would not be possible to discern checked and unchecked states.
Note that you can provide #description
text for each of the options individually, as illustrated in the second example for the radios form element, which also supports this ability.
color
Elements of type color provide a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in "#rrggbb" hexadecimal format. Only simple colors (with no alpha channel) are allowed. The values are compatible with CSS.
<?php
$form['color'] = array(
'#type' => 'color',
'#title' => 'Color',
);
?>
container
Returns HTML to wrap child elements in a container. Surrounds child elements with a <div>
and adds attributes such as classes or an HTML id.
<?php
if ($elements) {
// Also aid in theming of field widgets by rendering a classified
// container.
$addition[$field_name] = array(
'#type' => 'container',
'#attributes' => array(
'class' => array(
'field-type-' . backdrop_html_class($field['type']),
'field-name-' . backdrop_html_class($field_name),
'field-widget-' . backdrop_html_class($instance['widget']['type']),
),
),
'#weight' => $instance['widget']['weight'],
);
}
?>
contextual_links
A building block used in the creation of contextual links around other form elements.
$build['#contextual_links']['node'] = array('node', array($node->nid));
date
Format a date selection box. The #default_value will be today's date if no value is supplied. The format for the #default_value and the #return_value is an array with three elements with the keys: 'year', month', and 'day'. For example, array('year' => 2007, 'month' => 2, 'day' => 15)
(profile.module):
<?php
$fields[$category][$field->name] = array(
'#type' => 'date',
'#title' => check_plain($field->title),
'#default_value' => $edit[$field->name],
'#description' => _profile_form_explanation($field),
'#required' => $field->required
);
?>
details
Used for grouped form items. Can also be used as a theme wrapper for any renderable element, to surround it with a tag and add attributes such as classes or an HTML id.
Introduced in Backdrop 1.20.
The details
form element replaces the fieldset
element that Backdrop inherited from Drupal; although the latter element is still widely used in Backdrop, going forward, developers should use details
for collapsible groupings of other form elements (in both forms and general render arrays).
dropbutton
Format a drop-down menu containing a list of links to pages.
Note that any #attributes
will be applied to the ul
tag that contains the links, but there are additional div
wrapper classes around that.
<?php
$element['extra_actions'] = array(
'#type' => 'dropbutton',
'#links' => array(
'edit-details' => array(
'title' => t('Change view name/description'),
'href' => "admin/structure/views/nojs/config-details/$view->name",
'attributes' => array('class' => array('views-ajax-link')),
),
'analyze' => array(
'title' => t('analyze view'),
'href' => "admin/structure/views/nojs/analyze/$view->name/$display_id",
'attributes' => array('class' => array('views-ajax-link')),
),
'clone' => array(
'title' => t('clone view'),
'href' => "admin/structure/views/view/$view->name/clone",
),
'export' => array(), // Placeholder for export
'reorder' => array(
'title' => t('reorder displays'),
'href' => "admin/structure/views/nojs/reorder-displays/$view->name/$display_id",
'attributes' => array('class' => array('views-ajax-link')),
),
),
);
?>
Collect an email address from the user.
<?php
$form['mail'] = array(
'#type' => 'email',
'#title' => t('Your e-mail address'),
'#default_value' => $user->uid ? $user->mail : '',
'#required' => TRUE,
);
?>
fieldset
Represent a set of form controls optionally grouped under a common name.
Fieldsets were introduced in Drupal, and while still widely used in Backdrop, have now been superceded in many cases by the HTML 5 <details>
tag, which is now supported by most browsers. Going forward, for collapsible form elements, developers should use the details Form API element.
Note, though, that vertical tabs use fieldsets for grouping. If this element is part of a vertical tab group, or may be made part of a vertical tab group (by setting its #group property), it should remain a fieldset
element.
<?php
$form['comment'] = array(
'#type' => 'fieldset',
'#title' => t('Comment settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'additional_settings',
'#attributes' => array(
'class' => array('comment-node-type-settings-form'),
),
'#attached' => array(
'js' => array(backdrop_get_path('module', 'comment') . '/js/comment.admin.js'),
),
'#weight' => 25,
);
?>
field_ui_table
Creates a table for the "Manage fields" form of a bundle and its display.
<?php
$table = array(
'#type' => 'field_ui_table',
'#tree' => TRUE,
'#header' => array(
t('Label'),
t('Weight'),
t('Parent'),
t('Machine name'),
t('Field type'),
t('Widget'),
t('Operations'),
),
'#parent_options' => array(),
'#regions' => array(
'main' => array('message' => t('No fields are present yet.')),
'add_new' => array('title' => ' '),
),
'#attributes' => array(
'class' => array('field-ui-overview'),
'id' => 'field-overview',
),
);
?>
file
Format a file upload field.
Note: Backdrop will add the code enctype="multipart/form-data"
, required by browsers to handle files, so it's not necessary to include it yourself.
(file.module):
form
A form containing form elements.
head_tag
A render element to specify tags that are displayed in the <head> of the HTML page.
Note that although this render element can be used to create a general-purpose tag, the usage of head_tag
outside of the <head> is unsupported and will likely break in future versions of Backdrop.
<?php
function _backdrop_default_html_head() {
// Add default elements. Make sure the Content-Type comes first because the
// IE browser may be vulnerable to XSS via encoding attacks from any content
// that comes before this META tag, such as a TITLE tag.
$elements['system_meta_content_type'] = array(
'#type' => 'head_tag',
'#tag' => 'meta',
'#attributes' => array(
'charset' => 'utf-8',
),
// Security: This always has to be output first.
'#weight' => -1000,
);
// Show Backdrop and the major version number in the META GENERATOR tag.
// Get the major version.
list($version, ) = explode('.', BACKDROP_VERSION);
$elements['system_meta_generator'] = array(
'#type' => 'head_tag',
'#tag' => 'meta',
'#attributes' => array(
'name' => 'Generator',
'content' => 'Backdrop CMS ' . $version . ' (https://backdropcms.org)',
),
);
// Also send the generator in the HTTP header.
$elements['system_meta_generator']['#attached']['backdrop_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
return $elements;
}
?>
help
Add some help text to the page (the element will have a help
class and may be styled differently to other text).
Typically a bare #markup
element has no margins above or below, and it was not uncommon in the past to wrap such text in <p>
tags using the #prefix
and #suffix
properties. If the text is playing the role of help or explanatory text, you should use the help
element instead. For example, use this:
<?php
$form['foo'] = array(
'#type' => 'help',
'#markup' => t('This field does something.'),
);
?>
rather than this:
<?php
$form['foo'] = array(
'#markup' => t('This field does something.'),
'#prefix' => '<p>',
'#suffix' => '</p>',
);
?>
Though this element is commonly used in forms, it can also be used outside of forms as a renderable element.
<?php
$form['help'] = array(
'#type' => 'help',
'#markup' => t('This page lists all paths that have resulted in 404 errors and do not yet have any redirects assigned to them.'),
);
?>
hidden
Store data in a hidden form field.
(block.module):
<?php
$form['bid'] = array('#type' => 'hidden', '#value' => $bid);
?>
Note that if you plan to use JavaScript to change your hidden
element's value, you will need to use the #default_value
property rather than #value
.
Rendered output:
<input type="hidden" id="custId" name="custId" value="3487">
html_date
Format a date element.
<?php
$form['h5date'] = array(
'#type' => 'html_date',
'#title' => 'Date',
'#description' => 'A date.',
);
?>
Rendered output:
<label for="edit-h5date">Date </label>
<input id="edit-h5date" class="form-date" type="date" value="" name="h5date">
<div class="description">A date.</div>
html_datetime
Format both a date element and a time element together. Uses the browser to render the date and time pickers.
(node.module):
<?php
$form['author']['date'] = array(
'#type' => 'html_datetime',
'#title' => t('Authored on'),
'#default_value' => array(
'date' => format_date($node->created, 'custom', DATE_FORMAT_DATE),
'time' => format_date($node->created, 'custom', DATE_FORMAT_TIME),
),
'#attributes' => array(
'date' => array(
'min' => '1970-01-01',
'max' => '2037-12-31',
'placeholder' => t('e.g. @date', array(
'@date' => format_date(REQUEST_TIME, 'custom', DATE_FORMAT_DATE)
)),
),
'time' => array(
'placeholder' => t('e.g. @date', array(
'@date' => format_date(REQUEST_TIME, 'custom', DATE_FORMAT_TIME)
)),
),
),
'#description' => t('Leave blank to use the current time.'),
);
?>
Rendered Output:
<label for="edit-date">Authored on </label>
<div id="edit-date" class="container-inline">
<div class="form-item form-type-html-date form-item-date-date">
<input min="1970-01-01" max="2037-12-31" placeholder="e.g. 2024-11-01" id="edit-date-date" class="form-date" type="date" value="2020-09-10" name="date[date]">
</div>
<div class="form-item form-type-html-time form-item-date-time">
<input placeholder="e.g. 12:43:37" id="edit-date-time" class="form-time" type="time" value="19:00:00" name="date[time]" step="1">
</div>
</div>
<div class="description">Leave blank to use the current time.</div>
html_time
Format a time element. Uses the browser to render the time picker.
'html_time',
'#title' => 'Time',
'#description' => 'A time.',
);
?>
Rendered output:
<label for="edit-h5time">Time </label>
<input id="edit-h5time" class="form-time" type="time" value="" name="h5time" step="1">
<div class="description">A time.</div>
image_button
Format a form submit button with an image.
item
Generate a display-only form element allowing for an optional title and description.
Note: since this is a read-only field, setting the #required property will do nothing except theme the form element to look as if it were actually required (i.e. by placing a red star next to the #title).
Fields of type item
do not support the #attributes
property; use #wrapper_attributes
instead.
<?php
$form['from'] = array(
'#type' => 'item',
'#title' => t('From'),
'#markup' => $user->name .' <'. $user->mail .'>',
);
?>
link
A link with a title and target path.
There are two ways to add attributes (like classes) to the link. You can pass them directly as a '#attribute' property:
<?php
$form['link_1'] = array(
'#type' => 'link',
'#title' => t('Link 1'),
'#href' => 'mypath',
'#attributes' => array('class' => 'attribute-class'),
);
?>
Or you can pass them within the '#options' property (note, though, that the key within the '#options' property is 'attributes', not '#attributes').
<?php
$form['link_2'] = array(
'#type' => 'link',
'#title' => t('Link 2'),
'#href' => 'mypath',
'#options' => array(
'attributes' => array('class' => 'option-class'),
),
);
?>
You should not use both in the same link element. If you do, the '#options' attributes will be used and the '#attributes' property ignored.
<?php
$form['actions']['cancel'] = array(
'#type' => 'link',
'#title' => t('Cancel'),
'#href' => $options['path'],
'#options' => $options,
'#weight' => 1,
);
?>
link_field
Stores a title, href, and attributes in the database to assemble a link.
machine_name
Format a single-line text field to store a unique machine-readable name.
Provides a form element to enter a machine name, which is validated to ensure that the name is unique and does not contain disallowed characters. All disallowed characters are replaced with a replacement character via JavaScript.
The element validation checks that the submitted value:
- does not contain the replacement character only
- does not contain disallowed characters
- is unique; i.e., does not already exist
- does not exceed the maximum length (via #maxlength)
- cannot be changed after creation (via #disabled)
Non-standard form element properties:
- #machine_name: (array)
- exists: A function name to invoke for checking whether a submitted machine name value already exists. The submitted value is passed as argument. In most cases, an existing API or menu argument function can be re-used. The callback is only invoked, if the submitted value differs from the element's #default_value
- source: (optional) The #array_parents of the form element containing the human-readable name (i.e., as contained in the $form structure) to use as source for the machine name. Defaults to array('name').
- label: (optional) A text to display as label for the machine name value after the human-readable name form element. Defaults to "Machine name".
- replace_pattern: (optional) A regular expression (without delimiters) matching disallowed characters in the machine name. Defaults to '[^a-z0-9_]+'.
- replace: (optional) A character to replace disallowed characters in the machine name via JavaScript. Defaults to '_' (underscore). When using a different character, 'replace_pattern' needs to be set accordingly.
<?php
$form['machine_name'] = array(
'#type' => 'machine_name',
'#default_value' => $vocabulary->machine_name,
'#maxlength' => 21,
'#machine_name' => array(
'exists' => 'menu_edit_menu_name_exists',
),
);
?>
<?php
$form['menu_name'] = array(
'#type' => 'machine_name',
'#title' => t('Menu name'),
'#default_value' => $menu['menu_name'],
'#maxlength' => MENU_MAX_MENU_NAME_LENGTH_UI,
'#description' => t('A unique name to construct the URL for the menu. It must only contain lowercase letters, numbers and hyphens.'),
'#machine_name' => array(
'exists' => 'menu_edit_menu_name_exists',
'source' => array('title'),
'label' => t('URL path'),
'replace_pattern' => '[^a-z0-9-]+',
'replace' => '-',
),
// A menu's machine name cannot be changed.
'#disabled' => !empty($menu['old_name']) || isset($system_menus[$menu['menu_name']]),
);
?>
managed_file
Provides a complete ajax/progress aware widget for uploading a file and saving it to the {file_managed} table.
By default a simple Browse button is provided for choosing the file to upload. Once a file has been chosen it is uploaded automatically. The upload is via AJAX and a progress meter is displayed. The form's validate and submit handlers receive a file object ID in $form_state['values'] that represents the ID of the new file in the {file_managed} table.
The #managed_file element is expanded into a set of FAPI elements, including a '#submit' button (for removing the uploaded file), a '#file' element and a handful of '#hidden' and '#markup' elements to handle progress indication and displaying of already uploaded files.
Note: New files are uploaded with a status of 0 and are treated as temporary files which are removed after 6 hours via cron. Your module is responsible for changing the $file objects status to FILE_STATUS_PERMANENT and saving the new status to the database. Something like the following within your submit handler should do the trick.
<?php
// Load the file via file.fid.
$file = file_load($form_state['values']['my_file_field']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);
// Record that the module (in this example, user module) is using the file.
file_usage_add($file, 'user', 'user', $account->uid);
?>
(Without the call to file_usage_add, file_managed_file_validate produces an error upon saving the form, saying that the uploaded file may not be referenced.)
Once a file has been uploaded the file object's fid can be used as the #default_value for the form element. This will display an icon, a link to the file, and a remove button.
Clicking the remove button sets the value of the field to 0 and your module is responsible for actually removing the file from the files table and the file system using file_delete().
Non-standard form element properties:
- #progress_indicator: options are 'none', 'bar', and 'throbber', default is 'throbber'.
- #progress_message: (string) Progress message to display along with progress meter while a file is being uploaded. Defaults to NULL.
- #upload_validators: (array) an array of callback functions to perform validation of uploaded files.
- #upload_location (string) location on server where uploaded files should be stored. e.g.) 'public://files/my_files_director'
<?php
// Use the #managed_file FAPI element to upload an image file that will be tracked in the database.
$form['image_example_image_fid'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#description' => t('The uploaded image will be displayed on this page using the image style chosen below.'),
'#default_value' => config_get('image_example.settings', 'image_example_image_fid'),
'#upload_location' => 'public://image_example_images/',
);
?>
markup
Generate generic markup for display inside forms. Note that there is no need to declare a form element as #type = 'markup', as this is the default type.
Note: if you use markup, if the content will not be wrapped in tags (generally <p>
and <div>
), will fall outside of collapsed fieldsets. Please add wrapping tags if needed.
<?php
$form['contact_information'] = array(
'#markup' => variable_get('contact_form_information', t('You can leave us a message using the contact form below.')),
);
?>
number
Format a number (integer or decimal).
Note that the #size property is ignored by most browsers for the native number input, but is (currently) supported on Firefox.
<?php
$form['comment']['comment_per_page'] = array(
'#type' => 'number',
'#title' => t('Comments per page'),
'#default_value' => $node_type->settings['comment_per_page'],
'#required' => TRUE,
'#min' => 10,
'#max' => 1000,
'#step' => 10,
);
?>
Rendered output:
<label for="edit-comment-per-page">Comments per page <abbr class="form-required" title="This field is required.">*</abbr></label>
<input type="number" id="edit-comment-per-page" name="comment_per_page" value="600" step="10" min="10" max="1000" class="form-number required">
operations
Format a drop-down menu containing a list of links to pages that are typically administrative actions.
Note that any #attributes
will be applied to the ul
tag that contains the links, but there are additional div
wrapper classes around that.
The operations
element is nearly the same as the dropbutton
element, but has its own #theme property so that themers can, if they wish, distinguish between administrative action dropbuttons ('#type' => 'operations'
) and general-purpose dropbuttons ('#type' => 'dropbutton'
).
options
The 'options' form element type is useful when collecting a series of values in a list. The values within the list may optionally have unique keys, such as that in an array structure. In addition, a default choice (or several default choices) may be selected by the user.
<?php
$form['allowed_values'] = array(
'#type' => 'options',
'#title' => t('Allowed values list'),
'#description' => '',
'#default_value' => '',
'#default_value_allowed' => FALSE,
'#options' => $options,
'#element_validate' => array('list_allowed_values_setting_validate'),
'#field_has_data' => $has_data,
'#field' => $field,
'#field_type' => $field['type'],
'#key_type' => 'mixed', // Optimal for now.
'#key_type_toggle' => t('Custom keys'),
'#key_type_toggled' => $key_type_toggled,
'#access' => empty($settings['allowed_values_function']),
'#multiple' => !($field['cardinality'] == 1),
);
?>
password
Format a single-line password field that does not display its contents visibly.
(user.module):
<?php
$form['pass'] = array(
'#type' => 'password',
'#title' => t('Password'),
'#maxlength' => 64,
'#size' => 15,
);
?>
Rendered output:
<label for="edit-pass">Password <abbr class="form-required" title="This field is required.">*</abbr></label>
<input type="password" spellcheck="false" id="edit-pass" name="pass" size="60" maxlength="128" class="form-text required">
password_confirm
Format a pair of password fields, which do not validate unless the two entered passwords match.
(user.module):
<?php
$form['pass'] = array(
'#type' => 'password_confirm',
'#title' => t('Password'),
'#size' => 25,
);
?>
radio
Format a radio button.
Note: It is not necessary to add each radio individually. See Radios for how to add a complete set.
radios
Format a set of radio buttons.
Note that you can provide #description
text for each of the options individually, as illustrated in the second example, as well as other properties of individual radio
form elements, such as #indentation
.
(link.module):
<?php
$form['title'] = array(
'#type' => 'radios',
'#title' => t('Link Title'),
'#default_value' => $instance['settings']['title'],
'#options' => array(
'optional' => t('Optional Title'),
'required' => t('Required Title'),
),
'#description' => t('If the link title is optional or required, a field will be displayed to the end user. If the link title is static, the link will always use the same title.'),
);
?>
Rendered output:
<label for="edit-instance-settings-title">Link Title </label>
<div class="form-radios" id="edit-instance-settings-title">
<div class="form-item form-type-radio form-item-instance-settings-title">
<input type="radio" id="edit-instance-settings-title-optional" name="instance[settings][title]" value="optional" checked="checked" class="form-radio">
<label class="option" for="edit-instance-settings-title-optional">Optional Title </label>
</div>
<div class="form-item form-type-radio form-item-instance-settings-title">
<input type="radio" id="edit-instance-settings-title-required" name="instance[settings][title]" value="required" class="form-radio">
<label class="option" for="edit-instance-settings-title-required">Required Title </label>
</div>
</div>
<div class="description">If the link title is optional or required, a field will be displayed to the end user. If the link title is static, the link will always use the same title.</div>
<?php
$form['options']['status'] = array(
'#type' => 'radios',
'#title' => $node->nid ? t('Published state') : t('Publish action'),
'#options' => array(
NODE_PUBLISHED => $node->nid ? t('Published') : t('Publish now'),
NODE_NOT_PUBLISHED => $node->nid ? t('Draft') : t('Save as draft'),
),
'#default_value' => $status,
);
$form['options']['status'][NODE_PUBLISHED]['#description'] = t('Site visitors will be able to access this content.');
$form['options']['status'][NODE_NOT_PUBLISHED]['#description'] = t('Only the content creator or site administrators will be able to access this content.');
?>
Rendered output:
<label for="edit-status">Published state </label>
<div class="form-radios" id="edit-status">
<div class="form-item form-type-radio form-item-status">
<input type="radio" id="edit-status-1" name="status" value="1" checked="checked" class="form-radio">
<label class="option" for="edit-status-1">Published</label>
<div class="description">Site visitors will be able to access this content.</div>
</div>
<div class="form-item form-type-radio form-item-status">
<input type="radio" id="edit-status-0" name="status" value="0" class="form-radio">
<label class="option" for="edit-status-0">Draft </label>
<div class="description">Only the content creator or site administrators will be able to access this content.</div>
</div>
range
Form element that allows the user to enter a range of numbers, i.e., a minimum and maximum value.
scripts
An element that when rendered, creates the HTML to add a list of Javascript scripts to a page.
This takes the #items property as a structured array of queued cascading scripts in the form returned by backdrop_add_js().
<?php
function backdrop_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
if (!isset($javascript)) {
$javascript = backdrop_add_js();
}
if (empty($javascript)) {
return '';
}
...
// Render the HTML needed to load the JavaScript.
$elements = array(
'#type' => 'scripts',
'#items' => $items,
);
return backdrop_render($elements);
}
?>
search
Input element for search functionality.
<?php
$search['search']['search'] = array(
'#type' => 'search',
'#title' => t('Admin search'),
'#title_display' => 'invisible',
'#attributes' => array(
'placeholder' => t('Menu search'),
'autocomplete' => 'off',
'autocorrect' => 'off',
'autocapitalize' => 'off',
),
'#id' => 'admin-bar-search-items',
);
?>
select
Format a drop-down select for a single value, or scrolling selection box for multiple values. See #empty_option and #empty_value for an explanation of various settings for a select element, including behavior if #required is TRUE or FALSE.
styles
An element that when rendered, creates the HTML to add a list of stylesheets to a page.
This takes the #items property as a structured array of queued cascading stylesheets in the form returned by backdrop_add_css().
<?php
function backdrop_get_css($css = NULL, $skip_alter = FALSE) {
if (!isset($css)) {
$css = backdrop_add_css();
}
...
// Render the HTML needed to load the CSS.
$styles = array(
'#type' => 'styles',
'#items' => $css,
);
...
return backdrop_render($styles);
}
?>
submit
Format a form submit button.
<?php
$form['submit'] = array('#type' => 'submit', '#value' => t('Import'));
?>
tableselect
A table created with a far left column of radios or checkboxes.
Build the table headings and columns with the #headers property, and the rows with the #options property. See Adding checkboxes to a table for a full explanation.
Other settings:
- To set accessibility tags for the radios or checkboxes, build one of the cells in the #options property using the 'title' => array( 'data' => array(#title => 'mytitle'))) construction, as in the $options variable in the usage example below. Backdrop will create invisible label tags for the left column based on this value.
- To disable the default "check all" button for the checkboxes, set #js_select property to FALSE. This is FALSE by default for radios.
- Setting #multiple to TRUE will give you checkboxes instead of radios.
<?php
// Build the sortable table header.
$header = array(
'title' => array('data' => t('Title'), 'field' => 'n.title'),
'type' => array('data' => t('Type'), 'field' => 'n.type'),
'author' => t('Author'),
'status' => array('data' => t('Status'), 'field' => 'n.status'),
'changed' => array('data' => t('Updated'), 'field' => 'n.changed', 'sort' => 'desc')
);
...
//Get the node data.
$nids = $query
->fields('n',array('nid'))
->limit(50)
->orderByHeader($header)
->execute()
->fetchCol();
$nodes = node_load_multiple($nids);
...
//Build the rows.
$options = array();
foreach ($nodes as $node) {
...
$options[$node->nid] = array(
'title' => array(
'data' => array(
'#type' => 'link',
'#title' => $node->title,
'#href' => 'node/' . $node->nid,
'#options' => $l_options,
'#suffix' => ' ' . theme('mark', array('type' => node_mark($node->nid, $node->changed))),
),
),
'type' => check_plain(node_type_get_name($node)),
'author' => theme('username', array('account' => $node)),
'status' => $node->status ? t('published') : t('not published'),
'changed' => format_date($node->changed, 'short'),
);
//For simplicity, this example omits the code to set the operations column.
...
//Build the tableselect.
$form['nodes'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
'#empty' => t('No content available.'),
);
?>
tel
Form element to enter a telephone number.
<?php
$form['phone'] = array(
'#type' => 'tel',
'#title' => t('Your phone number'),
'#required' => $phone == 'required',
);
?>
textarea
Format a multiple-line text field.
<?php
$form['keywords'] = array(
'#title' => t('Keywords'),
'#type' => 'textarea',
'#description' => t ('The comment will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
'#default_value' => isset( $context['keywords']) ? backdrop_implode_tags($context['keywords']) : '',
);
?>
textfield
Format a single-line text field.
(forum.module):
<?php
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
);
?>
text_format
A text-format-enabled version of a textarea.
Non-standard Properties:
- #format: the format to apply. If you want to use the default format, set this property to NULL in your form constructor function, and the filter system will handle the rest.
- #base_type (optional): defaults to 'textarea'. This makes it possible to also attach the text format selector to other form element types, such as textfields.
<?php
$form['description'] = array(
'#type' => 'text_format',
'#title' => t('Description'),
'#default_value' => $term->description,
'#format' => $term->format,
'#weight' => 0,
);
?>
token
Store token data in a hidden form field (generally used to protect against cross-site forgeries).
Note: A token element is automatically added to each Backdrop form by backdrop_prepare_form(), so you don't generally have to add one yourself.
url
Format a url field.
value
A form value that is internal to the form and never displayed to the screen.
(node.module):
<?php
$form['vid'] = array('#type' => 'value', '#value' => $node->vid);
?>
Note that you can also simply store arbitrary variables in $form['#foo']
instead, as long as '#foo
' does not conflict with any other internal property of the Form API.
vertical_tabs
Formats all child fieldsets as vertical tabs. Non-child fieldsets can be added to the vertical tab by setting their #group to the vertical tab's element name.
$form['additional_settings'] = array(
'#type' => 'vertical_tabs',
'#weight' => 99,
'#attached' => array(
'js' => array(backdrop_get_path('module', 'user') . '/js/user.admin.js'),
),
);
weight
Format a weight selection menu.
(menu.module):
<?php
$form['weight'] = array(
'#type' => 'weight',
'#title' => t('Weight'),
'#default_value' => $edit['weight'],
'#delta' => 10,
'#description' => t('Optional. In the menu, the heavier items will sink and the lighter items will be positioned nearer the top.'),
);
?>
Properties
#access
Whether the element is accessible or not; when FALSE, the element is not rendered and the user submitted value is not taken into consideration.
TRUE or FALSE.
#action
The path to which the form will be submitted.
An internal path.
<?php
$form['#action'] = url('comment/reply/'. $edit['nid']);
?>
#after_build
An array of function names which will be called after the form or element is built.
<?php
$form['file_public_path'] = array(
'#type' => 'textfield',
'#title' => t('Public file system path'),
'#default_value' => variable_get('file_public_path', conf_path() . '/files'),
'#maxlength' => 255,
'#description' => t('A local file system path where public files will be stored. This directory must exist and be writable by Backdrop. This directory must be relative to the Backdrop installation directory and be accessible over the web.'),
'#after_build' => array('system_check_directory'),
);
?>
#aggregate_callback
A function to call to aggregate the items within the groups arranged by the #group_callback function. See backdrop_pre_render_styles().
#ajax
An array of elements whose values control the behavior of the element with respect to the Backdrop AJAX framework.
AJAX (Asynchronous Javascript and XML) is a term used for dynamic communication between the browser and the server, without page reloads. In a nutshell an AJAX request follows these steps:
- Backdrop builds a form element with a set of #ajax properties. The
misc/ajax.js
file is included on the page automatically. - ajax.js finds all the form elements on the page that have an #ajax['callback'] or an #ajax['path'] set and adds an event handler for the #ajax['event'] set on that form element.
- When the #ajax['event'] occurs on the element (such as 'click'), the AJAX request is made to the Backdrop path of the element's #ajax['path']. If an #ajax['callback'] has been specified (the normal case), the Backdrop path will be
system/ajax
. - Form information gets processed, and the function specified in #ajax['callback'] is called. #ajax['callback'] can return either HTML, a renderable array, or an array of AJAX commands.
- While the user waits for the callback to execute a throbber or progress bar is shown as determined by #ajax['progress']. The result is returned to the original page containing the form element.
- ajax.js gets the result. If it is HTML and #ajax['wrapper'] is set, the HTML replaces the element specified by #ajax['wrapper']. If it is an array of AJAX commands, the commands are executed and inserts the returned HTML into the #ajax['wrapper'].
Example usages of basic AJAX and AJAX commands are provided in the Examples module.
#ajax['callback']
Specifies the name of a callback function which will be called during an AJAX call. It can return HTML, a renderable array, or an array of AJAX Commands. This callback function is given the $form
and $form_state
parameters, allowing it to produce a result, which it returns for rendering.
Note: #ajax['callback'] and #ajax['path'] are mutually exclusive. 'callback' is easier to use and requires less code setup, but may not provide the capabilities required for some functions. When you can, use 'callback'.
String containing a function name.
(poll.module):
<?php
/**
* Implementation of hook_form().
*/
function poll_form(&$node, $form_state) {
...
$form['choice_wrapper']['poll_more'] = array(
'#type' => 'submit',
'#value' => t('More choices'),
'#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
'#weight' => 1,
'#submit' => array('poll_more_choices_submit'), // If no javascript action.
'#ajax' => array(
'callback' => 'poll_choice_js',
'wrapper' => 'poll-choices',
'method' => 'replace',
'effect' => 'fade',
),
);
...
}
/**
* Menu callback for AJAX additions. Render the new poll choices.
*/
function poll_choice_js($form, $form_state) {
return $form['choice_wrapper']['choice'];
}
?>
#ajax['effect']
Specifies the effect used when adding the content from an AJAX request.
String. Possible values: 'none' (default), 'fade', 'slide'. If the interface elements library is installed, any effect with the name effectToggle may also be used.
#ajax['event']
When this event occurs to this element, Backdrop will perform an HTTP request in the background via Javascript.
String. Possible values: Any valid jQuery event, including 'mousedown' (for submit, imagebutton, and button), 'blur' (for textfield and textarea), 'change' (for select). Note that #ajax['event'] does not need to be explicitly specified. Although it can be manually set, usually the default value will be sufficient.
#ajax['keypress']
If set to TRUE, then the element's #ajax['event'] will be triggered if the ENTER key is pressed while the element has focus.
#ajax['method']
Modify the behavior of the returned HTML from an AJAX request when inserting into the #ajax['wrapper']. If not set, the returned HTML will replace the contents of the wrapper element, but it's also possible to use any of the available jQuery operations for DOM manipulation.
String. Possible values: 'replace' (default), 'after', 'append', 'before', 'prepend'.
#ajax['path']
This is the Backdrop menu path for a callback function which will generate HTML and return the string of HTML to Backdrop. The result will replace the div specified in #ajax['wrapper']. This property is infrequently used, because it is set automatically if using the #ajax['callback'] property. When using #ajax['callback'] the path is automatically set to system/ajax
, which provides a menu callback that can be used for many situations.
Note: 'path' and 'callback' are mutually exclusive.
String containing a Backdrop menu path.
#ajax['prevent']
A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'. Multiple events may be specified separated by spaces. For example, when binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior.
String. Possible values: One or more jQuery events, with multiple events separated by space characters.
#ajax['progress']
Choose either a throbber or progress bar that is displayed while awaiting a response from the callback, and add an optional message.
Array.
Possible keys: 'type', 'message', 'url', 'interval'
Possible values:
- #ajax['progress']['type'] String. Possible values: 'throbber' (default), 'bar'.
- #ajax['progress']['message'] String. An optional message to the user; should be wrapped with t().
- #ajax['progress']['url'] String. The optional callback path to use to determine how full the progress bar is (as defined in progress.js). Only useable when 'type' is 'bar'.
- #ajax['progress']['interval'] String. The interval to be used in updating the progress bar (as defined in progress.js). Ony used if 'url' is defined and 'type' is 'bar'.
(file.module):
<?php
$ajax_settings['progress']['type'] ? $ajax_settings['progress']['type'] == 'bar' : 'throbber';
$ajax_settings['progress']['message'] = NULL;
$ajax_settings['effect'] = 'none';
$element['remove_button'] = array(
'#name' => implode('_', $element['#parents']) . '_remove_button',
'#type' => 'submit',
'#value' => t('Remove'),
'#validate' => array(),
'#submit' => array('file_managed_file_submit'),
'#limit_validation_errors' => array($element['#parents']),
'#ajax' => $ajax_settings,
'#weight' => -5,
);
?>
#ajax['trigger_as']
For a non-submit, non-button element, allows selection of the submit element which will be activated when the element is triggered. For example, if a select element is ajax-enabled, and it changes, an element identified by #ajax['trigger_as']['name'] or #ajax['trigger_as']['value'] will be used as the triggering element, especially for button-level validation.
Array.
Possible values
Note that if #tree == TRUE, #name encodes the parents of the element in it, as when used with form_set_error(), i.e. "level1][level2][element".
#ajax['wrapper']
This property defines the HTML id attribute of an element on the page which will be replaced by the html returned by the #ajax['path'] or #ajax['callback'] function. Usually, a div element is used as the wrapper, as it provides the most flexibility for placement of elements before, after, or inside of its HTML tags. This property is required for using AJAX requests in on a form element. Note that the entire element with this ID is replaced, not just the contents of the element.
String containg a valid id attribute of an HTML element on the same page. This must not contain the '#' character that a selector would have.
(book.module):
<?php
// Add a drop-down to select the destination book.
$form['book']['bid'] = array(
'#type' => 'select',
'#title' => t('Book'),
'#default_value' => $node->book['bid'],
'#options' => $options,
'#access' => (bool) $options,
'#description' => t('Your page will be a part of the selected book.'),
'#weight' => -5,
'#attributes' => array('class' => array('book-title-select')),
'#ajax' => array(
'callback' => 'book_form_update',
'wrapper' => 'edit-book-plid-wrapper',
'effect' => 'fade',
'speed' => 'fast',
),
);
?>
#allow_focus
This property, when set to TRUE, turns a #disabled element into a read-only element.
It is common in Backdrop to make a normally editable element non-editable by setting #disabled = TRUE, but in that case, the element value will not be included in the form submission in $_POST
. To include its value, set $allow_focus to TRUE.
TRUE or FALSE.
<?php
// A disabled textedit field that won't be submitted.
$form['edit_1'] = array(
'#type' => 'textfield',
'#title' => t('Field 1'),
'#default_value' => 'Some value',
'#disabled' => TRUE,
);
// A disabled textedit field that is read-only and will be submitted.
$form['edit_2'] = array(
'#type' => 'textfield',
'#title' => t('Field 2'),
'#default_value' => 'Some value',
'#disabled' => TRUE,
'#allow_focus' => TRUE,
);
?>
#array_parents
(read-only, and mostly internal). The array of names of the element's parents (including itself) in the form. This will always match the structure of $form. It is different from #parents in that #parents lists only the structure used in $form_state['values'], which is flat unless #tree is set to TRUE. Please see the complete comparison between #parents and #array_parents.
#attached
Allows loading of CSS, Javascript, libraries, or custom types when the form is built.
A keyed array of type => value pairs, where the type (most often 'css', 'js', and 'library') determines the loading technique, and the value provides the options presented to the loader function. See the example below and the loader functions backdrop_add_css(), backdrop_add_js(), backdrop_add_library(), etc.
See backdrop_process_attached() for additional information.
(AJAX Example):
<?php
$form['#attached']['css'] = array(
backdrop_get_path('module', 'ajax_example') . '/ajax_example.css',
);
$form['#attached']['js'] = array(
backdrop_get_path('module', 'ajax_example') . '/ajax_example.js',
);
?>
The above javascript #attach could also be written as:
<?php
$form['#attached']['js'] = array(
backdrop_get_path('module', 'ajax_example') . '/ajax_example.js' => array(
'type' => 'file',
),
);
?>
and inline javascript can be loaded with the javascript as the key of the array, as described in backdrop_add_js().
Adding settings
You add a javascript setting by using the 'data' key (as php keys can't be arrays):
<?php
$settings = array('id' => 'mymodule-element-1');
$form['#attached']['js'][] = array(
'data' => array('mymodule' => $settings),
'type' => 'setting',
);
?>
Usage example (contact.pages.inc):
<?php
if (!$user->uid) {
$form['#attached']['library'][] = array('system', 'jquery.cookie');
$form['#attributes']['class'][] = 'user-info-from-cookie';
}
?>
#attributes
Additional HTML attributes, such as 'class' can be set using this mechanism.
Any HTML attribute not covered by other properties, e.g. class (for control types), enctype (for forms).
Note: If you are altering an existing form via hook_form_alter() or a similar means, be careful with this property! You will probably want to add to the existing array rather than writing over it, so don't follow this usage example exactly.
#autocomplete_path
The path the AJAX autocomplete script uses as the source for autocompletion.
(node.module):
<?php
$form['author']['name'] = array(
'#type' => 'textfield',
'#title' => t('Authored by'),
'#maxlength' => 60,
'#autocomplete_path' => 'user/autocomplete',
'#default_value' => $node->name,
'#weight' => -1,
);
?>
#base_type
The form element #type to use for the 'value' element when expanding an element into a base element with text format selector attached.
This should be the machine name of one of the text format types.
#browser_view
The name of the View to use as a browser for managed files.
FALSE or the name of the View.
#built
Used to ascertain whether or not a form element has been built yet.
TRUE or FALSE.
INTERNAL. See the _form_builder function in form.inc.
#button_type
Adds a CSS class to the button, in the form form-[button_type_value]. Note that this does NOT set the HTML attribute type of the button.
String.
#children
Internal. The rendered child elements of an element. Automatically assigned by backdrop_render(), unless already set. In rare cases, you may use #children to override the output of rendered child elements, for example in a #theme_wrappers or #post_render callback. Normally, you should not have to use #children, use regular child elements instead. (See actions for an example.)
String representing the rendered child elements of an element.
(theme_container()):
Example in a #theme_wrappers callback.
<?php
function theme_container($variables) {
$element = $variables['element'];
...
return '<div' . backdrop_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
}
?>
#collapsed
Specifies whether a fieldset that is collapsible is initially collapsed.
TRUE or FALSE.
<?php
$form['comment'] = array(
'#type' => 'fieldset',
'#title' => t('Comment settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'additional_settings',
'#attributes' => array(
'class' => array('comment-node-type-settings-form'),
),
'#attached' => array(
'js' => array(backdrop_get_path('module', 'comment') . '/js/comment.admin.js'),
),
'#weight' => 25,
);
?>
#collapsible
Specifies whether a fieldset can be collapsed.
TRUE or FALSE.
<?php
$form['comment'] = array(
'#type' => 'fieldset',
'#title' => t('Comment settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#group' => 'additional_settings',
'#attributes' => array(
'class' => array('comment-node-type-settings-form'),
),
'#attached' => array(
'js' => array(backdrop_get_path('module', 'comment') . '/js/comment.admin.js'),
),
'#weight' => 25,
);
?>
#cols
How many columns wide the textarea should be (see also #rows).
A positive number.
(aggregator.module):
<?php
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Description'),
'#default_value' => $edit['description'],
'#cols' => 60,
'#rows' => 5,
);
?>
#commands
A form property containing AJAX commands of the form returned by ajax_command_*(). See the AJAX Framework for details on usage.
<?php
function config_export_single_form_update_type($form, &$form_state) {
// Empty out the configuration value field.
$form['export']['#value'] = '';
$form['export']['#rows'] = 12;
// Because we need to replace both the configation name select and the
// textarea, this requires using AJAX commands instead of a simple return.
$commands = array();
$commands[] = ajax_command_replace('#edit-config-type-wrapper', backdrop_render($form['config_name']));
$commands[] = ajax_command_replace('#edit-export-wrapper', backdrop_render($form['export']));
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));
return array(
'#type' => 'ajax',
'#commands' => $commands,
);
}
?>
#config
Name of configuration file where form submission values are to be stored.
If #config
is used at the top level of the form array (see Example 1 below), all submitted values in the form will be saved under the corresponding key in the configuration file. If form sub-elements or groups of sub-elements have their own #config
keys, then values of those elements and their children will be saved to that configuration file (see Example 2 below).
Once this property is set, the form variable must be passed to system_settings_form()
, which will add the appropriate handlers to store the form values.
String containing a configuration file name, with the '.json' extension removed.
Example 1
<?php
$form['#config'] = 'admin_bar.settings';
$form['margin_top'] = array(
'#type' => 'checkbox',
'#title' => t('Adjust top margin'),
'#default_value' => $config->get('margin_top'),
'#description' => t('Shifts the entire site content down to make room for the administration bar. If disabled, absolute- or fixed-positioned page elements may be covered by the administration bar.'),
);
// ...
return system_settings_form($form);
?>
Example 2
All sub-elements of the fieldset $form['user_login']
will be stored to system.core.json, while the rest of the elements will be stored in user.flood.json
<?php
$form['#config'] = 'user.flood';
// User login settings.
$form['user_login'] = array(
'#type' => 'fieldset',
'#title' => t('User login'),
'#weight' => -2,
'#config' => 'system.core',
);
$form['user_login']['user_login_method'] = array(
'#type' => 'radios',
'#title' => t('Users may log in using'),
'#options' => array(
USER_LOGIN_USERNAME_OR_EMAIL => t('Username or email address'),
USER_LOGIN_USERNAME_ONLY => t('Username'),
USER_LOGIN_EMAIL_ONLY => t('Email address'),
),
'#default_value' => $core_config->get('user_login_method'),
);
// ...
return system_settings_form($form);
?>
#default_tab
The default open tab.
String containing the HTML ID of the fieldset element for the default tab. The default value is an empty string, which results in the first tab having the focus. The elements's HTML ID typically takes the form of "edit-ARRAY_KEY".
<?php
$form['vertical_tabs'] = array(
'#type' => 'vertical_tabs',
'#default_tab' => 'edit-tab2',
);
$form['tab1'] = array(
'#type' => 'fieldset',
'#title' => t('Tab 1'),
'#group' => 'vertical_tabs',
);
$form['tab1']['field1'] = array(
'#title' => t('Field 1'),
'#type' => 'textfield',
);
$form['tab2'] = array(
'#type' => 'fieldset',
'#title' => t('Tab 2'),
'#group' => 'vertical_tabs',
);
$form['tab2']['field2'] = array(
'#title' => t('Field 2'),
'#type' => 'textfield',
);
?>
#default_value
The value of the form element that will be displayed or selected initially if the form has not been submitted yet. Should NOT be confused with #value, which is a hard-coded value the user cannot change!
Mixed.
(forum.module):
<?php
$form['body'] = array(
'#type' => 'textarea',
'#title' => t('Body'),
'#default_value' => $node->body,
'#required' => TRUE,
);
?>
#default_value_allowed
Indicates whether the end user should be able to modify the default value when editing an options list.
TRUE or FALSE.
#default_value_pattern
If allowing dynamic default value keys, such as a token, specify a regular expression pattern that will also be allowed as a default value. Include pattern delimiters.
#delta
Number of weights to have selectable. For example, with $delta => 10, the weight selection box would display numbers from -10 to 10.
A positive number.
(menu.module):
<?php
$form['weight'] = array(
'#type' => 'weight',
'#title' => t('Weight'),
'#default_value' => $edit['weight'],
'#delta' => 10,
'#description' => t('Optional. In the menu, the heavier items will sink and the lighter items will be positioned nearer the top.'),
);
?>
#description
The description of the form element. Make sure to enclose inside the t() function so this property can be translated.
Mixed.
(menu.module):
<?php
$form['weight'] = array(
'#type' => 'weight',
'#title' => t('Weight'),
'#default_value' => $edit['weight'],
'#delta' => 10,
'#description' => t('Optional. In the menu, the heavier items will sink and the lighter items will be positioned nearer the top.'),
);
?>
#details
Full details information for a details element.
#disabled
Disables (greys out) a form input element. Setting #disabled to TRUE results in user input being ignored, regardless of how the element is themed or whether JavaScript is used to change the control's attributes.
TRUE or FALSE.
<?php
if (isset($disabled[$name])) {
$form['theme_settings'][$name]['#disabled'] = TRUE;
}
?>
#editor_uploads
Specifies whether uploads are allowed.
TRUE or FALSE.
<?php
$form['body'] = array(
'#type' => 'text_format',
'#title' => t('Block content'),
'#default_value' => $edit['body']['value'],
'#format' => $edit['body']['format'],
'#editor_uploads' => TRUE,
'#rows' => 8,
'#required' => TRUE,
);
?>
#element_validate
A list of custom validation functions. The validation functions must use form_error() or form_set_error() to flag the element as having an error if the validation fails.
An array of function names to be called to validate this element (and/or its children).
A validation function for an element takes $element, $form_state, and $form as parameters, and has the form:
<?php
function myelement_validate($element, &$form_state, $form) {
if (empty($element['#value'])) {
form_error($element, t('This field is required.'));
}
}
?>
For the function name, you can use any valid PHP Callback, for example:
-
'#element_validate' => array('myelement_validate')
, a function name; -
'#element_validate' => array('CLASS::METHOD')
, a static class method; -
'#element_validate' => array(array('CLASS', 'METHOD'))
, another way of specifying a static class method; -
'#element_validate' => array(array($my_object, 'METHOD'))
, a method of a class object; -
'#element_validate' => array(array($this, 'METHOD'))
, a method of a class object, when this property is used within another method of the same class.
Note: If you are altering an existing form element via hook_form_alter() or a similar means, be careful with this property! You will probably want to add to the existing array rather than writing over it, so in that case don't follow this usage example exactly.
You'll notice that the validation function below includes only the first two arguments. $form is the same as $form_state['complete form'], so the third parameter is in fact contained in the second parameter.
<?php
$form['max_filesize'] = array(
'#type' => 'textfield',
'#title' => t('Maximum upload size'),
'#default_value' => $settings['max_filesize'],
'#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))),
'#size' => 10,
'#element_validate' => array('_file_generic_settings_max_filesize'),
'#weight' => 5,
);
...
function _file_generic_settings_max_filesize($element, &$form_state) {
if (!empty($element['#value']) && !is_numeric(parse_size($element['#value']))) {
form_error($element, t('The "!name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('!name' => t($element['title']))));
}
}
?>
#empty
Text to display if the #options property is empty.
Text, enclosed in the t() translation function.
#empty_option
The label to show for the initial option denoting no selection in a select element. By default, the label is automatically set to "- Select -" for a required field and "- None -" for an optional field.
Text, enclosed in the t() translation function.
Note: Use of this property plays a part in several possible states for a select field:
- If #required is TRUE and there is no #default_value, an empty option is added to the select control to force the user to make an active choice.
- If #empty_value or #empty_option is set and #required is FALSE (default), an empty option is added to the select control, allowing the user to choose nothing.
- If none of #required, #empty_value, #empty_option, and #default_value are set, then no empty option is added to the select control. This leaves the control in a slightly illogical state, since all user agents automatically preselect the first available option.There's no way for the user to select nothing, and the user is also not forced to make an active decision.
#empty_value
The value for the initial option denoting no selection in a select element, which is used to determine whether the user submitted a value or not.
Defaults to empty string. Can be anything except NULL.
Note: Use of this property plays a part in several possible states for a select field:
- If #required is TRUE and there is no #default_value, an empty option is added to the select control to force the user to make an active choice.
- If #empty_value or #empty_option is set and #required is FALSE (default), an empty option is added to the select control, allowing the user to choose nothing.
- If none of #required, #empty_value, #empty_option, and #default_value are set, then no empty option is added to the select control. This leaves the control in a slightly illogical state, since all user agents automatically preselect the first available option. There's no way for the user to select nothing, and the user is also not forced to make an active decision.
#error
INTERNAL. Indicates whether or not a form element has been flagged as having an error.
#executes_submit_callback
Indicates whether or not the submit handler should be run when the form is submitted using this button element.
TRUE or FALSE.
#extended
Indicates whether the managed file element is extended with additional properties. See file_field_widget_form().
(file_module_text.module)
<?php
$form['nested']['file'] = array(
'#type' => 'managed_file',
'#title' => t('Managed file'),
'#upload_location' => 'public://test',
'#progress_message' => t('Please wait...'),
'#extended' => (bool) $extended,
'#size' => 13,
);
?>
#field_prefix
Text or code that is placed directly in front of a field. This can be used to prefix a field with a constant string. It should be translated, normally. If it is not already wrapped in a safe markup object, will be filtered for XSS safety.
Note that (unlike #prefix
and #suffix
), #field_prefix
(and #field_suffix
) work properly with #states
.
Any HTML markup in #field_prefix
(or #field_suffix
) should be complete, as both will be independently wrapped in span
tags. That is, you should not put an opening tag in #field_prefix
and its close in #field_suffix
. Use #prefix
and #suffix
to wrap the field in another tag.
Mixed.
<?php
$form['site_403'] = array(
'#type' => 'textfield',
'#title' => t('Default 403 (access denied) page'),
'#default_value' => variable_get('site_403', ''),
'#size' => 40,
'#description' => t('This page is displayed when the requested document is denied to the current user. If unsure, specify nothing.'),
'#field_prefix' => url(NULL, NULL, NULL, TRUE) . (variable_get('clean_url', 0) ? '' : '?q=')
);
?>
#field_suffix
Text or code that is placed directly after a field. This can be used to add a unit to a field (often a #number
field).
Note that (unlike #prefix
and $suffix
), #field_prefix
(and #field_suffix
) work properly with #states
.
Mixed.
<?php
$form['settings_general']['upload_usersize_default'] = array(
'#type' => 'textfield',
'#title' => t('Default total file size per user'),
'#default_value' => $upload_usersize_default,
'#size' => 5,
'#maxlength' => 5,
'#description' => t('The default maximum size of all files a user can have on the site.'),
'#field_suffix' => t('MB')
);
?>
#format
A format type for the text_format
element.
This should be the machine name of one of the text format types.
#group
Specifies a group that can be used to group fieldsets into vertical tabs.
A string where the value is used for the id of a form element with the #type of vertical_tabs.
<?php
$form['email'] = array(
'#type' => 'vertical_tabs',
);
...
$form['email_admin_created'] = array(
'#type' => 'fieldset',
'#title' => t('Welcome (new user created by administrator)'),
'#description' => t('Edit the welcome e-mail messages sent to new member accounts created by an administrator.'),
'#group' => 'email'
);
?>
#group_callback
A function to call to group #items to enable the use of fewer tags by aggregating files and/or using multiple @import statements within a single tag. See backdrop_pre_render_styles().
#has_garbage_value
An indicator used in image buttons to indicate not to pass the value of that element.
#header
Column headers.
Associative array where the keys are the field names to use for each column, and the values are the translated text to display for each column header.
#href
Target path for a link.
String giving the path of a link.
#https
A property of a form that specifies whether it should be posted as https.
TRUE or FALSE
<?php
function authorize_filetransfer_form($form, &$form_state) {
global $is_https;
$form = array();
// If possible, we want to post this form securely via HTTPS.
$form['#https'] = TRUE;
...
}
?>
#id
Internal. Used to populate form elements' id property. In rare cases, you can set this value yourself on a form element, to override the default setting.
HTML ID string.
#indentation
An integer quantity that specifies the level of indentation to be applied to this form element. Used for conveying hierarchical relationships between form elements and/or dependencies.
Note that for checkboxes
, radios
, and select
form elements, distinct values of indentation can be applied to the individual checkboxes, radio buttons, and select values, as illustrated in the usage example.
Introduced in Backdrop 1.25.0.
Integer between 0 and 5. (Higher levels of indentation are not currently supported in core CSS.)
<?php
$form['checkboxes'] = array(
'#type' => 'checkboxes',
'#title' => 'Indented checkboxes',
'#options' => array(
0 => 'No indentation',
'foo' => 'One indentation',
3 => 'No indentation 2',
'bar' => 'Two indentations',
),
);
$form['checkboxes']['foo']['#indentation'] = 1;
$form['checkboxes']['bar']['#indentation'] = 2;
?>
#input
INTERNAL. Indicates whether or not input is possible for this form element.
#items
A list of CSS or JS files provided to the #styles or #scripts form element.
<?php
function backdrop_get_css($css = NULL, $skip_alter = FALSE) {
if (!isset($css)) {
$css = backdrop_add_css();
}
...
// Render the HTML needed to load the CSS.
$styles = array(
'#type' => 'styles',
'#items' => $css,
);
...
return backdrop_render($styles);
}
?>
#js_select
Whether to include a select all checkbox.
TRUE to add a select all box to each row of the table, FALSE to omit the select all box. Only applies if #multiple is also TRUE.
#key_type
The method by which keys are determined for each value in an option list.
'mixed', 'numeric', 'associative', 'custom', or 'none'. See options_element_info() for description.
#key_type_toggle
If specified for an 'option' element, a checkbox will be added that allows the user to toggle between the current key type and the "custom" key type, letting them customize the keys as desired. This option has no effect with the "none" key type.
A test string.
#key_type_toggled
Determine if the toggle checkbox is set or not by default.
TRUE or FALSE.
#limit
The maximum number of options that can be added to an options list. Defaults to 100.
Any nonnegative integer.
#limit_validation_errors
Provides an array of sections which are parts of $form_state['values'] which should be validated, implying that sections which are not listed should not be validated. This is normally used in multistep forms in the case of a "back" button, for example, where '#limit_validation_errors' => array() would mean not to validate anything as form values on the current page are to be discarded anyway. #limit_validation_errors does not have any effect if #submit is not set. More discussion is in the form_set_error() documentation.
Array indicating sections of the $form_state['values'] which should be validated.
#links
A structured array giving a list of links used in a dropbutton or operations element.
An array of arrays, each link array containing the following keys:
- title (required) — the title of the link. Should be wrapped in t().
- href (required) — the destination of the link.
- attributes (optional) — any attributes, such as 'class', to be applied to the <a> tag.
- query (optional) — additional query parameters. See the documentation for url() for further information.
#markup
Used to set HTML that will be output on the form.
Text (valid HTML).
<?php
$form['from'] = array(
'#type' => 'item',
'#title' => t('From'),
'#markup' => check_plain($user->name) . ' <' . check_plain($user->mail) . '>',
);
?>
#max
Establishes a maximum value for a number element.
Any valid numeric quantity.
<?php
$form['comment']['comment_per_page'] = array(
'#type' => 'number',
'#title' => t('Comments per page'),
'#default_value' => $node_type->settings['comment_per_page'],
'#required' => TRUE,
'#min' => 10,
'#max' => 1000,
'#step' => 10,
);
?>
#maxlength
The maximum amount of characters to accept as input.
A positive number.
(forum.module):
<?php
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
);
?>
#method
The HTTP method with which the form will be submitted.
GET or POST. Default is POST.
(node.module):
<?php
$form['#method'] = 'post';
?>
#min
Establishes a minimum value for a number element.
Any legal numeric value.
<?php
$form['comment']['comment_per_page'] = array(
'#type' => 'number',
'#title' => t('Comments per page'),
'#default_value' => $node_type->settings['comment_per_page'],
'#required' => TRUE,
'#min' => 10,
'#max' => 1000,
'#step' => 10,
);
?>
#multiple
Indicates whether the user may select more than one item.
TRUE or FALSE.
<?php
return array(
'#type' => 'select',
'#title' => $title,
'#default_value' => $value,
'#options' => $options,
'#description' => $description,
'#multiple' => $multiple,
'#size' => $multiple ? min(12, count($options)) : 0,
'#weight' => -15,
);
?>
#name
String.
#open
Initial collapsed/expanded display.
#optgroups
If nesting of options is supported, up to one level. This is used when building a select HTML element that uses optgroups. Defaults to FALSE.
TRUE or FALSE.
#options
There are two use cases for this property:
- Selectable options for a form element that allows multiple choices (checkboxes, radios, select, tableselect).
- Alternative way of specifying attributes for a link element.
Important note: You should not mix integer and string keys in a list of options; the keys should be either all integers or all strings. When PHP compares integers to strings (something that's likely to happen anytime someone is checking whether a particular key was chosen), it casts the strings to integers, which can give unexpected results. See, for example, backdrop/backdrop-issues#6024.
- In multiple-choice form elements: An array in the form of
<?php
array(t('Display value 1'), t('Display value 2'))
?>
or
<?php
array(
'return_value1' => t('Display Value 1'),
'return_value2' => t('Display Value 2'),
)
?>
if specific return values are required. If returned values are identical to displayed values, you can use backdrop_map_assoc() as in the example below. The #options property needs special handling for checkboxes, and works completely differently for tableselect. - In link elements: An array of values that could be supplied as the third argument to l().
<?php
$form['undergraduate']['school_country'] = array(
'#type' => 'select',
'#options' => backdrop_map_assoc(array(t('UK'), t('Other'))),
'#title' => t('In what country is your college or university located?'),
);
?>
#options_readonly
Indicates whether an option list is read-only.
TRUE or FALSE.
#parents
Identifies parent form elements. See #tree and #parents in the handbook and the complete comparison between #parents and #array_parents.
An array of element names.
#parent_options
Options to be passed to the parent HTML element.
<?php
$table = array(
'#type' => 'field_ui_table',
'#tree' => TRUE,
'#header' => array(
t('Field'),
t('Weight'),
t('Parent'),
t('Label'),
array('data' => t('Format'), 'colspan' => 3),
),
'#regions' => array(
'visible' => array('message' => t('No field is displayed.')),
'hidden' => array('title' => t('Hidden'), 'message' => t('No field is hidden.')),
),
'#parent_options' => array(),
'#attributes' => array(
'class' => array('field-ui-overview'),
'id' => 'field-display-overview',
),
// Add Ajax wrapper.
'#prefix' => '<div id="field-display-overview-wrapper">',
'#suffix' => '</div>',
);
?>
#password_shown
Indicates whether the password is (initially) shown or greeked on a password form element.
TRUE or FALSE.
(form.inc)
<?php
$element['pass1'] = array(
'#type' => 'password',
'#title' => t('New password'),
'#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
'#required' => $element['#required'],
'#attributes' => array('class' => array('password-field')),
'#password_strength' => TRUE,
'#password_shown' => FALSE,
'#password_toggle' => FALSE,
);
?>
#password_strength
Specifies whether to provide an evaluation of password strength on a password form element.
TRUE or FALSE.
<?php
$form['admin_account']['account']['pass'] = array(
'#title' => st('Password'),
'#type' => 'password',
'#required' => TRUE,
'#weight' => 0,
'#password_toggle' => TRUE,
'#password_strength' => TRUE,
);
?>
#password_toggle
Specifies whether to allow the user to toggle between showing and hiding a password in a password field element.
TRUE or FALSE.
<?php
$form['admin_account']['account']['pass'] = array(
'#title' => st('Password'),
'#type' => 'password',
'#required' => TRUE,
'#weight' => 0,
'#password_toggle' => TRUE,
'#password_strength' => TRUE,
);
?>
#placeholder
Defines a short prompt or example text to be displayed in an input field using HTML5's placeholder attribute.
Text, enclosed in the t() translation function.
<?php
$form['password'] = array(
'#type' => 'password',
'#title' => t('Password'),
'#placeholder' => t('Enter password'),
);
?>
#post_render
Function(s) to call after rendering in backdrop_render has occured. The named function is called with two arguments, the rendered element and its children. It returns the (potentially) altered) element content.
An array of function names to call.
Note: If you are altering an existing form via hook_form_alter() or a similar means, be careful with this property! You will probably want to add to the existing array rather than writing over it, so don't follow this usage example exactly.
<?php
$form['admin']['#post_render'] = array('admin_form_html_cleanup');
?>
This example would call admin_form_html_cleanup($content, $element) after $element has been rendered to $content via backdrop_render(). $content may then be modified and must be returned.
#prefix
Text or markup to include before the form element. Also see #suffix.
You can use #prefix
and #suffix
to wrap the element in another HTML tag, as in the example below.
Note: do not use #field_prefix
and #field_suffix
in the same manner, as these properties require complete HTML tags (HTML elements that have both opening and closing tags).
Mixed.
(poll.module):
<?php
$form['choice'] = array(
'#type' => 'fieldset',
'#title' => t('Choices'),
'#prefix' => '<div class="poll-form">',
'#suffix' => '</div>',
'#tree' => TRUE,
);
?>
#pre_render
Function(s) to call before rendering in backdrop_render() has occured. The function(s) provided in #pre_render receive the element as an argument and must return the altered element.
An array of function names to call.
Note: If you are altering an existing form via hook_form_alter() or a similar means, be careful with this property! As demonstrated here, you will probably want to add to the existing array rather than writing over it.
<?php
// Prepend #pre_render callback to replace field value with user notice
// prior to rendering.
if (!isset($element['value']['#pre_render'])) {
$element['value']['#pre_render'] = array();
}
array_unshift($element['value']['#pre_render'], 'filter_form_access_denied');
...
function filter_form_access_denied($element) {
$element['#value'] = t('This field has been disabled because you do not have sufficient permissions to edit it.');
return $element;
}
?>
This example would call filter_form_access_denied($element) before the $element has been rendered via backdrop_render. $element may then be modified and is returned for rendering.
#printed
INTERNAL. Used to determine whether or not a form element has been printed yet.
#process
An array of functions that are called when an element is processed. Using this callback, modules can "register" further actions. For example, the "radios" form type is expanded to multiple radio buttons using a processing function.
Array of function names (strings).
(system.module) in system_element_info()
:
Note: If you are altering an existing form via hook_form_alter() or a similar means, be careful with this property! You will probably want to add to the existing array rather than writing over it, so don't follow this usage example exactly.
<?php
$types['radios'] = array(
'#input' => TRUE,
'#process' => array('form_process_radios'),
'#theme_wrappers' => array('radios'),
'#pre_render' => array('form_pre_render_conditional_form_element'),
);
?>
In this example, the function form_process_radios
is called; the entire radios element is passed in as the argument. This function expands a radios element into individual radio buttons.
#processed
INTERNAL. Used to ascertain whether or not a form element has been processed (ie: expanded to multiple elements).
#progress_indicator
What type of progress indicator to display during file uploads.
'throbber' or 'bar' or 'none'.
<?php
$form['upload'] = array(
'#type' => 'managed_file',
'#title' => t('Upload a new file'),
'#upload_location' => file_upload_destination_uri($options),
'#upload_validators' => file_get_upload_validators($options),
'#progress_indicator' => 'bar',
'#pre_render' => array('file_managed_file_pre_render', 'file_upload_validators_pre_render'),
'#default_value' => isset($form_state['storage']['upload']) ? $form_state['storage']['upload'] : NULL,
);
?>
#progress_message
Message to display while a file is uploading.
A string or NULL.
<?php
$form['nested']['file'] = array(
'#type' => 'managed_file',
'#title' => t('Managed file'),
'#upload_location' => 'public://test',
'#progress_message' => t('Please wait...'),
'#extended' => (bool) $extended,
'#size' => 13,
);
?>
#redirect
Indicates where the person who is using the form should be redirected when the form submits.
string
<?php
$form['#redirect'] = 'admin/config/media/file-system/settings';<br>
?>
#regions
Property of a 'field_ui_table' element.
<?php
$table = array(
'#type' => 'field_ui_table',
'#tree' => TRUE,
'#header' => array(
t('Field'),
t('Weight'),
t('Parent'),
t('Label'),
array('data' => t('Format'), 'colspan' => 3),
),
'#regions' => array(
'visible' => array('message' => t('No field is displayed.')),
'hidden' => array('title' => t('Hidden'), 'message' => t('No field is hidden.')),
),
'#parent_options' => array(),
'#attributes' => array(
'class' => array('field-ui-overview'),
'id' => 'field-display-overview',
),
// Add Ajax wrapper.
'#prefix' => '<div id="field-display-overview-wrapper">',
'#suffix' => '</div>',
);
?>
#required
Indicates whether or not the element is required. This automatically validates for empty fields, and flags inputs as required. File fields are NOT allowed to be required.
TRUE or FALSE.
(forum.module):
<?php
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
);
?>
#required_message
Form elements that have the #required
property will display a generic error if the value is left empty. You can set #required_message
to a custom message to display instead.
Introduced in Backdrop 1.23.0.
A translated string.
<?php
$form['checkboxes'] = array(
'#type' => 'checkboxes',
'#title' => t('Checkboxes'),
'#options' => $options,
'#required' => TRUE,
'#required_message' => t('Please choose at least one option.'),
);
?>
#resizable
Whether users should be allowed to resize the text area.
TRUE or FALSE.
#return_value
Value element should return when selected.
Mixed.
(poll.module):
<?php
$form['morechoices'] = array(
'#type' => 'checkbox',
'#title' => t('Need more choices'),
'#return_value' => 1,
'#default_value' => 0,
'#description' => t("If the amount of boxes above isn't enough, check this box and click the Preview button below to add some more."),
);
?>
#rows
How many rows high the textarea should be (see also #cols).
A positive number.
(aggregator.module):
<?php
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Description'),
'#default_value' => $edit['description'],
'#cols' => 60,
'#rows' => 5,
);
?>
#size
Width of the textfield (in characters) or size of multiselect box (in lines).
A positive number.
<?php
$form['admin']['homepage'] = array(
'#type'=> 'textfield',
'#title'=> t('Homepage'),
'#maxlength'=> 255,
'#size'=> 30,
'#default_value'=> $edit['homepage'],
);
?>
#src
The URL of the image of the button.
A URL.
#states
Adds JavaScript to the element to allow it to have different active states.
A structured array describing the different JavaScript states that can be applied to the element when certain conditions are met. Please read the extensive description of this feature at backdrop_process_states().
#step
Establishes that the value must be offset from the minimum value (or zero if there is no minimum) by an integral multiple of this value.
Any positive numeric value or 'any' if there is no step requirement.
<?php
$form['comment']['comment_per_page'] = array(
'#type' => 'number',
'#title' => t('Comments per page'),
'#default_value' => $node_type->settings['comment_per_page'],
'#required' => TRUE,
'#min' => 10,
'#max' => 1000,
'#step' => 10,
);
?>
#submit
A list of custom submit functions that will be called when the form or element is submitted. This is usually to add additional submit functions to a form, or to use an alternate function rather than the default form submission function which is the form ID with _submit appended to it.
An array of function names to be called upon submission of this form (after successful validation).
A submission function for a form takes $form and $form_state as parameters. For example:
<?php
function test_form_submit($form, &$form_state) {
// Do something with the values submitted in $form_state['values'].
}
?>
For the function name, you can use any valid PHP Callback, for example:
-
'#submit' => array('myelement_validate')
, a function name; -
'#submit' => array('CLASS::METHOD')
, a static class method; -
'#submit' => array(array('CLASS', 'METHOD'))
, another way of specifying a static class method; -
'#submit' => array(array($my_object, 'METHOD'))
, a method of a class object; -
'#submit' => array(array($this, 'METHOD'))
, a method of a class object, when this property is used within another method of the same class.
#suffix
Text or markup to include after the form element. Also see #prefix.
Mixed.
(poll.module):
<?php
$form['choice'] = array(
'#type' => 'fieldset',
'#title' => t('Choices'),
'#prefix' => '<div class="poll-form">',
'#suffix' => '</div>',
'#tree' => TRUE,
);
?>
#summary
Summary information for a details element.
#tag
A form property used to specify a tag to be added to page HTML.
<?php
function _backdrop_default_html_head() {
// Add default elements. Make sure the Content-Type comes first because the
// IE browser may be vulnerable to XSS via encoding attacks from any content
// that comes before this META tag, such as a TITLE tag.
$elements['system_meta_content_type'] = array(
'#type' => 'head_tag',
'#tag' => 'meta',
'#attributes' => array(
'charset' => 'utf-8',
),
// Security: This always has to be output first.
'#weight' => -1000,
);
// Show Backdrop and the major version number in the META GENERATOR tag.
// Get the major version.
list($version, ) = explode('.', BACKDROP_VERSION);
$elements['system_meta_generator'] = array(
'#type' => 'head_tag',
'#tag' => 'meta',
'#attributes' => array(
'name' => 'Generator',
'content' => 'Backdrop CMS ' . $version . ' (https://backdropcms.org)',
),
);
// Also send the generator in the HTTP header.
$elements['system_meta_generator']['#attached']['backdrop_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
return $elements;
}
?>
#theme
Theme function to call for element. It must render this element and all of its child elements.
The name of a theme function, without the initial 'theme_'.
(node.module):
<?php
$data['actions']['output'][] = array(
'#theme' => 'menu_local_action',
'#link' => $item,
);
?>
#theme_wrappers
Theme function to call for element, after the element and children are rendered, but before the #post_render functions are called.
The name of a theme function, without the initial 'theme_'.
(system.module from definition of default properties for a form):
#title
The title of the form element. Make sure to enclose inside the t() function so this property can be translated.
Mixed.
(aggregator.module):
<?php
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Description'),
'#default_value' => $edit['description'],
'#cols' => 60,
'#rows' => 5,
);
?>
#title_display
Indicates how the label should be rendered. The label includes the #title and the required marker, if #required. If the #title is empty but the field is #required, the label will contain only the required marker.
String.
Possible values:
- before: The label is output before the element. This is the default for most elements.
- after: The label is output after the element. For example, this is used for radio and checkbox #type elements as set in system_elements().
- invisible: #title is rendered as a label element before the form element in the page markup, and is made invisible with the
.element-invisible
system CSS class (system.base.css). This makes #title remain available to screen-reader users, but hides it from being displayed visually in the browser. - attribute: Set the title attribute on the element to create a tooltip but output no label element. This is supported only for checkboxes and radios in form_pre_render_conditional_form_element(). It is used where a visual label is not needed, such as a table of checkboxes where the row and column provide the context. The tooltip will include the title and required marker.
(block.module):
#token_types
A list of token types included in a form element that may contain tokens within its '#value'
property.
The form element should include '#element_validate' => array('token_element_validate')
in its properties as in the example.
<?php
$form['email_admin_created']['user_mail_register_admin_created_subject'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#default_value' => $mail_config->get('register_admin_created_subject'),
'#maxlength' => 180,
'#element_validate' => array('token_element_validate'),
'#token_types' => array('user'),
);
?>
#tree
Used to allow collections of form elements. Normally applied to the "parent" element, as the #tree property cascades to sub-elements. Use where you previously used ][ in form_ calls. For more information, see #tree and #parents in the handbook.
TRUE or FALSE.
<?php
$form['status'] = array(
'#type' => 'checkboxes',
'#default_value' => $status,
'#options' => $options,
'#tree' => TRUE,
);
$required = array('block', 'filter', 'system', 'user', 'watchdog');
foreach ($required as $require) {
$form['status'][$require] = array(
'#type' => 'hidden',
'#value' => 1,
'#suffix' => t('required'),
);
}
?>
#type
Used to determine the type of form element.
<?php
$form['submit'] = array('#type' => 'submit', '#value' => t('Import'));
?>
#upload_location
Location to upload a managed file to.
NULL for the default, or a URI specifying the location.
<?php
$form['image'] = array(
'#type' => 'managed_file',
'#title' => t('Background image'),
'#description' => $upload_description,
'#default_value' => $this->settings['image'],
'#upload_location' => 'public://hero/',
'#upload_validators' => $upload_validators,
'#weight' => -10,
);
?>
#upload_validators
A nested array of functions to validate uploaded files. See file_get_upload_validators() for the validator categories.
<?php
$form['upload'] = array(
'#type' => 'managed_file',
'#title' => t('Upload a new file'),
'#upload_location' => file_upload_destination_uri($options),
'#upload_validators' => file_get_upload_validators($options),
'#progress_indicator' => 'bar',
'#pre_render' => array('file_managed_file_pre_render', 'file_upload_validators_pre_render'),
'#default_value' => isset($form_state['storage']['upload']) ? $form_state['storage']['upload'] : NULL,
);
?>
#validate
A list of custom validation functions that need to be passed. This is usually used to add additional validation functions to a form, or to use an alternate function rather than the default form validation function which is the form ID with _validate appended to it.
An array of function names to be called to validate this form.
A validation function for a form takes $form and $form_state as parameters and should use form_set_error() if the form values do not pass validation. For example:
<?php
function test_form_validate($form, &$form_state) {
if ($form_state['values']['name'] == '') {
form_set_error('name', t('You must select a name for this group of settings.'));
}
}
?>
For the function name, you can use any valid PHP Callback, for example:
-
'#validate' => array('myelement_validate')
, a function name; -
'#validate' => array('CLASS::METHOD')
, a static class method; -
'#validate' => array(array('CLASS', 'METHOD'))
, another way of specifying a static class method; -
'#validate' => array(array($my_object, 'METHOD'))
, a method of a class object; -
'#validate' => array(array($this, 'METHOD'))
, a method of a class object, when this property is used within another method of the same class.
(node.module):
Note: If you are altering an existing form via hook_form_alter() or a similar means, be careful with this property! You will probably want to add to the existing array rather than writing over it, so don't follow this usage example exactly.
<?php
// Node types:
$types = array_map('check_plain', node_get_types('names'));
$form['advanced']['type'] = array(
'#type' => 'checkboxes',
'#title' => t('Only of the type(s)'),
'#prefix' => '<div class="criterion">',
'#suffix' => '</div>',
'#options' => $types,
);
$form['advanced']['submit'] = array(
'#type' => 'submit',
'#value' => t('Advanced search'),
'#prefix' => '<div class="action">',
'#suffix' => '</div>',
);
$form['#validate'][] = 'node_search_validate';
?>
#validation_arguments
INTERNAL
#value
Used to set values that cannot be edited by the user. Should NOT be confused with #default_value, which is for form inputs where users can override the default value.
If the Token module is enabled, you can use tokens within this field, but you must set the #token_types property to specify the allowed types of tokens. See https://docs.backdropcms.org/form_api/token_types for details.
Mixed (text or numbers).
<?php
$form['submit'] = array('#type' => 'submit', '#value' => t('Import'));
?>
#value_callback
Specifies the name of a custom value function that implements how user input is mapped to an element's #value property.
A single function name to be called to set the value of this element.
A value function for an element takes $element, $input and $form_state as parameters, and has the form:
<?php
// Essentially we use the managed_file type, extended with some enhancements.
$element_info = element_info('managed_file');
$element += array(
'#type' => 'managed_file',
'#default_value' => isset($items[$delta]) ? $items[$delta] : $defaults,
'#upload_location' => file_field_widget_uri($field, $instance),
'#upload_validators' => file_field_widget_upload_validators($field, $instance),
'#value_callback' => 'file_field_widget_value',
'#process' => array_merge($element_info['#process'], array('file_field_widget_process')),
// Allows this field to return an array instead of a single value.
'#extended' => TRUE,
);
...
function file_field_widget_value($element, $input = FALSE, $form_state) {
if ($input) {
// Checkboxes lose their value when empty.
// If the display field is present make sure its unchecked value is saved.
$field = field_widget_field($element, $form_state);
if (empty($input['display'])) {
$input['display'] = $field['settings']['display_field'] ? 0 : 1;
}
}
?>
#weight
Used to sort the list of form elements before being output; lower numbers appear before higher numbers.
A positive or negative number (integer or decimal).
(book.module):
<?php
$form['parent'] = array(
'#type' => 'select',
'#title' => t('Parent'),
'#default_value' => ($node->parent ? $node->parent : arg(4)),
'#options' => book_toc($node->nid),
'#weight' => -15,
'#description' => t('The parent that this page belongs in. Note that pages whose parent is <top-level> are regarded as independent, top-level books.'),
);
?>
#wrapper_attributes
Attributes that should be added to the wrapper around a form item.