Last Updated: February 25, 2016
·
1.725K
· 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.
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7

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(
      'type'=>'textfield',
      'title'=>'Enter your email:',
    );
    $form['submit'] = array(
      'type'=>'submit',
      'value'=>'Subscribe',
    );
   return $form;
}

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

drupal_get_form('test_form');

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'];
  if(empty($v['email'])){
    // When you call form_set_error(), that stops the form 
    // submission process
    form_set_error('email','Oops, email address is required!');
  }
  if(!valid_email_address($v['email'])){
    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'];
  MyModule_subscribe($v['email']);
}

Building forms in Drupal is quite fun!