So you need a Form. Where do you start?
If you're anything like me (which I hope you are, because you're reading this!), then you'll want to look at the Drupal Forms API.
What is the Drupal Forms API?
The Forms API is part of Drupal that is used to generate Forms. It allows you to use all the features of Drupal (access control, input filtering, theme control), and apply them to a form.
It also allows you to customize how the form is submitted, and gives you control of the validation process before the form is submitted (it also gives you some handy pre-built validation functions too).
This really is only scratching the surface, but you've got to start somewhere.
An Example
Ok, on to the code. We'll start by creating a simple form and calling it from a node.
The code below will build you a very simple form with a text input, a select input and a submit button.
function example_form() { $form = array(); $form['container'] = array( '#type' => 'fieldset', '#title' => t('Example Form'), '#description' => t('Elements to demonstrate a basic Drupal Form.') ); $form['container']['text'] = array ( '#type' => 'textfield', '#title' => t('Enter Text Here') ); $form['container']['select'] = array ( '#type' => 'select', '#title' => t('An Example Select Element'), '#options' => array( t('Option 1'), t('Option 2') ) ); $form['submit'] = array ( '#type' => 'submit', '#value' => t('Submit Me') ); return $form; } return drupal_get_form('example_form');
How does it work?
Drupal has several built in Form functions, that deal with building and rendering your forms, and all you have to do is provide an array of information to the build functions. In this case, we build the form array, then return it.
When we call drupal_get_form, we pass I the name of the function that returns the form, and Drupal does the rest. Easy, no?
The Form Array
OK, so now we should look at what the array actually means.
$form = array();
Here we simply create an empty array that will contain the form definition.
$form['container'] = array(
Now, we need to start adding basic elements to our form. So let's start with a field set to contain our form. We need to make the array contain an element called 'container' (This can be any name, I've just chosen container because it serves well as an example), which is itself an array of all the information needed to define the fieldset.
'#type' => 'fieldset',
Here we are declaring the type of the form element. The type will define what kind of form element you want (text, radio boxes, select, etc), and therefore what other fields you are going to use, so it's a good idea to define this one first. If you don't set this, it will default to 'markup' (More on this later!).
'#title' => t('Example Form'),
This is the text that gets displayed in relation to this element. If you have defined a fieldset, the corresponding HTML that is generated will be a legend, however for all other form elements this will be a label. Don't forget to use the t() function!
'#description' => t('Elements to demonstrate a basic Drupal Form.')
This element simply adds a div to the page that can be themed with your informative text, so the user knows what the purpose of the form field is.
);
And finally close the array.
Now $form has all the information needed to build a simple fieldset.
Shall we put some more elements in?
A Text Input
This is one of the most widely used form fields, so it is important to know how do ad one to your form.
$form['container']['text'] = array (
This line adds the text input as a child of the fieldset. We then just add the same elements to it as before.
'#type' => 'textfield', '#title' => t('Enter Text Here') );
Now, for the select element.
$form['container']['select'] = array (
Again, we add this element as a child of the fieldset.
'#type' => 'select', '#title' => t('An Example Select Element'), '#options' => array(
This property is how we add the options to the select dropdown list.
t('Option 1'), t('Option 2') )
This array contains the options for the dropdown. Note this can come from a function call ( '#options => build_options_array() ).
);
And again close the array.
The last element is the submit button.
$form['submit'] = array ( '#type' => 'submit', '#value' => t('Submit Me') ); </ph> <p>Now, finally return the $form.</p> <p>So, we are now ready to see how the form looks.</p> <p>To build the form, call <code class="code_inline">drupal_get_form()</code> and pass in the name of the function that returns the form.</p> <php>return drupal_get_form('example_form');
This call can be placed in a node, or you can add it to the hook_menu of a module.
Submitting the Form.
As you can see, you now have a nice form. However, nothing happens when you try to submit it. This is because we haven't defined a submit handler.
Submit handlers are functions that get executed when a form is submitted. They deal with processing the data in the form, such as writing it to a database table, or sending an email.
There's the code to simply send a email with our data in it:
function example_form_submit($form, &$form_state) { $values = $form_state['values']; $to = '[your email address]'; $subject = 'Email from Example Form '; $message ="Form contents:\r\n "; $message .= "Text Field: $values[text] \r\n"; $message .= "Select Field: $values[select] \r\n"; mail($to, $subject, $message); drupal_set_message(t('Email has been sent.')); }
This code will simply send an email to the specified email address, and return you to the form (this is done automatically) with the message 'Email has been sent' displayed at the top of the page. Easy!
What about Validation?
Validation is extremely important in form submissions, as you want to make sure you capture the correct information. Drupal allows you to specify a validation functions for the whole form, or for specific elements. Validation takes place before the form is submitted, so we can do checks here for the absence of data. If the checks fail, we know the submission will not take place.
A form-wide Validation function
Drupal automatically checks for the presence of data in required fields, so we don't need to worry about that, but we can write a check to ensure only a number is entered into a textfield (useful if you want to deal with money for example).
Here's the code to do that:
function example _form_validate($form, &$form_state){ if( !is_numeric(trim($form_state['values']['text'])) ) { form_set_error('text', t('Please ensure the text is a number.')); } }
All we do is a simple check to see if the value of the of the input is a number. If that fails, set an error against the form. This stops the submission process, and Drupal re-displays the form with an error message. It also Shows you which form field needs attention. This is done by the form_set_error function.
The first parameter sets a field to display the errors against, the second parameter sets the error text to display at the top of the page.
I hope you found this article useful. We have only scratched the surface of this topic, Drupal forms are very powerful, allowing you to create multi-step forms, dynamically change parts of the form, auto-fill values and much, much more!
Keep checking back to the next instalment!
Happy Coding!

