Last Updated: February 25, 2016
· donutdan4114

Building a simple Drupal form

Have you ever wanted to make a custom form? Maybe you have a custom module and you find the Drupal Form API confusing?

The Drupal Form API can be daunting.

Here is a simple example of how to create a custom form.
Let's pretend you have a custom module called MyModule:

function MyModule_test_form(){
    $form['email'] = array(
      'title'=>'Enter your email:',
    $form['submit'] = array(
   return $form;

To use the form, you just need to use drupalgetform().


You can learn more about the Form API from here: http://drupal.org/node/751826

To me, the most powerful thing about the Form API is the way you can handle form validation and submission.

Let's write a validation handler to make sure the email that is entered is valid:

function MyModule_test_form_validate($form, &$form_state){
  $v = $form_state['values'];
    // When you call form_set_error(), that stops the form 
    // submission process
    form_set_error('email','Oops, email address is required!');
    form_set_error('email', "Oops, that's not an email address!");

If the form does pass validation, we can now submit the form.

function MyModule_test_form_submit($form, &$form_state){
  $v = $form_state['values'];

Building forms in Drupal is quite fun!