Objectives & prerequisites
- Learn about different elements you can add to a form.
- Learn where to find more information about all the element types and their properties.
Drupal offers a wide range of elements you can add to a form. In addition to the elements in core, you can create your own elements (they're plugins, just like blocks), or download contrib modules that define form elements.
Available element types
The list of available element types is part of the reference documentation.
→ open up the page on Form and render elements and filter on 'FormElement' to get the full list.
The list of element types includes:
- Checkbox
- Radio
- Date
- URL (link)
- Textfield
- Textarea
- Select
- File
- ...
Example
Here's the code that produces this form.
You'll notice a pattern in how each field is added to the form.
Breakdown
First we add two fields:
Then we add fieldset named 'colours' that will group the next three fields:
Then we add three fields to that fieldset. Notice the structure of the array of each of three fields:
The first array key of these three fields is 'colours', which is the array key of the fieldset:
- First add a fieldset
- Then add fields to that fieldset using the fieldset's array key as the fields' first array key.
Then we add another fieldset and add two fields to that fieldset.
We finalise with a submit button.
Activity
Throughout these examples we've demonstrated some properties:
- Identify which fields are mandatory, and how that was defined.
- Identify which field has a default value and which has a placeholder value. Default values and placeholder values are similar but not identical. What's the difference?
- Compare the
primary_colourandsecondary_colourfields. Their definition is almost identical; only the#typeproperty is different- Change the only the type field, and see what happens. Field types with option lists include
select,radiobuttons, andcheckboxes.
- Change the only the type field, and see what happens. Field types with option lists include
Activity
Build a Christmas dinner subscription form that asks for:
- First name, last name
- Number of guests (select list, choices range from 1 - 10)
- Number of meat/fish choices (number field)
- Number of vegetarian choices (number field)
- Number of vegan choices (number field)
- Whether your table would like to be alcohol-free or not.
Summary
- There's a wide range of form elements available by default.
- You can find a list of all form elements at https://api.drupal.org/api/drupal/elements/.
- You can group elements together using fieldsets.