Understanding Forms in Drupal

Embed Size (px)

Citation preview

  • 8/16/2019 Understanding Forms in Drupal

    1/12

    Web applications today are being used in all kinds of industries. They need to take in and process a lot of us

    data. The capturing of the data happens through HTML forms which let you create different types of input fi

    like textboxes, radio buttons etc. using HTML tags. These forms get difficult to maintain or update if they ar

    written directly in the HTML code. Drupal provides a very good way of defining forms directly in your PHP co

    while the form generation is done by Drupal itself. This makes it easy for you to create and maintain forms. I

    this article we are going to see how we can create forms in Drupal. The final code can be cloned fromGithub.

    The drupal_get_form function – Form generation in

    Drupal

    The whole magic of form creation in Drupal is performed by the function drupal_get_form. This functio

    returns a renderable form array to the Drupal system. It takes an argument as the form_id: a unique identifie

    identify the form, and if a function with the same name exits then that function is called to build it. You can

    more aboutdrupal_get_form at the

    linkhttps://api.drupal.org/api/drupal/includes!form.inc/function/drupal_get_form/7

    Creating a basic form in DrupalLet’s start by creating a small module which will create a menu callback and then on that menu callback cre

    form using thedrupal_get_form function. To create a module add a folder to your Drupal

    installation sites\all\modules\drupalform and add two files to

    it: drupalform.info and drupalform.module with the following code:

    drupalform.info

    name = drupalform

    description = This module creates a form using Drupal.

    core = 7.x

    drupalform.module

  • 8/16/2019 Understanding Forms in Drupal

    2/12

  • 8/16/2019 Understanding Forms in Drupal

    3/12

      return $items;

    }

    function drupalform_form1() {

    $form = array();

    $form['name']=array(

    '#type'=>'textfield',

    '#title'=>t('Enter your name'),

    '#description'=>t('Your first name goes here')

    );

    $form['last_name']=array(

    '#type'=>'textfield',

    '#title'=>t('Enter your Last name'),

    '#description'=>t('Your Last name goes here')

    );

    $form['email']=array(

    '#type'=>'textfield',

    '#title'=>t('Enter your email'),

    '#description'=>t('Your email goes here'));

    $form['country']=array(

    '#type'=>'select',

    '#title'=>t('Select your country'),

    '#options'=>array('USA','UK','France','Japan')

    );

    $form['submit']=array(

    '#type'=>'submit',

    '#value'=>t('Submit')

    );

    return $form;

    }

    In the above code in the implementation of hook_menu we create a menu item

     

  • 8/16/2019 Understanding Forms in Drupal

    4/12

    the form_id "drupalform_form1". The functiondrupalform_form1 returns the form array which we wa

    create.

    In the function drupalform_form1 we create three text fields: name, last_name, email, and one select b

    for the country. In the select box we specify the options of the country with an array. We have also added a

    Submit button, so the user can actually submit the form. Now you should be able to go to your menu url: /drupalform/form1 and see the form as follows

    Validating a Drupal formDrupal uses naming conventions heavily to identify which functions to call on which events. The complete

    Drupal hook system is based on naming conventions. Similarly, the function called to validate your form dat

    has to follow the naming convention _validate and it will be passed the form_state as a

    variable.

    Hence, for our form the function name will be:drupalform_form1_validate($form, $form_state).

    The values which the user has entered will be resent in an arra   form state 'values'  with the sa

  • 8/16/2019 Understanding Forms in Drupal

    5/12

    function drupalform_form1_validate($form, $form_state) {

    if(empty($form_state['values']['name']))

    form_set_error('name','Name cannot be empty');

    else if(empty($form_state['values']['last_name']))

    form_set_error('last_name','Last name cannot be empty');else if(filter_var($form_state['values']['email'], FILTER_VALIDATE_EMAIL

    form_set_error('email','Email is not valid');

    }

    In the above function we check if the name and last_name are not empty and that the email is valid. If that i

    the case we set a form error using the Drupal function form_set_error. This will display the error to the

    user and the form will not be submitted.

    If you submit the form by entering an empty name you should see the following error on the screen:

    Submitting a Drupal form

    Similar to the validation function the submit function is also called based on the naming convention and the

    function name should be_submit. Again, the variable $form_state will be passed to it. Ou

    submit function will thus be defined as:

  • 8/16/2019 Understanding Forms in Drupal

    6/12

      //Depending on the type of form you can add the logic 

    //to store the details of the form

    //by adding it in a Drupal table. 

    //or sending a mail to the admin 

    //Storing in a file 

    //or pass it to some other service 

    drupal_set_message("Form has been submitted"); 

    }

    Now if we pass all the valid fields you will get the following message on screen.

    Using Field sets in Drupal Forms to separate element

    Sometimes when the form is bigger and has many fields you might want to break it into small sections so th

    the form seems more logical to the user. To do this you can create fieldsets in Drupal to create groups of fiel

    To create a fieldset called basicdetails to hold the fields we defined above we will have to update

    the drupalform_form1 as follows

    function drupalform_form1() { 

    $form = array(); 

    $form['basicdetails']=array( '#type'=>'fieldset', 

    '#title'=>t('Enter your Basic details below'), 

    '#description'=>t('These are all madatory') 

  • 8/16/2019 Understanding Forms in Drupal

    7/12

      $form['basicdetails']['name']=array( 

    '#type'=>'textfield', 

    '#title'=>t('Enter your name'), 

    '#description'=>t('Your first name goes here') 

    ); 

    $form['basicdetails']['last_name']=array( 

    '#type'=>'textfield', 

    '#title'=>t('Enter your Last name'), 

    '#description'=>t('Your Last name goes here') 

    ); 

    $form['basicdetails']['email']=array( 

    '#type'=>'textfield', 

    '#title'=>t('Enter your email'), 

    '#description'=>t('Your email goes here') 

    ); 

    $form['submit']=array( 

    '#type'=>'submit', 

    '#value'=>t('Submit') ); 

    return $form; 

    }

    This will create a separate fieldset as shown below

  • 8/16/2019 Understanding Forms in Drupal

    8/12

    The different form elements that can be used in Drup

    forms

    Drupal provides a great number of different types of fields which we can use in our forms. I will update our f

    to use some of these by creating two more field sets for address details and additional details.

    The updated code is below:

    function drupalform_form1() { 

    $form = array(); 

    $form['basicdetails']=array( 

    '#type'=>'fieldset', 

    '#title'=>t('Enter your Basic details below'), 

    '#description'=>t('These are all madatory') ); 

    $form['basicdetails']['name']=array( 

    ' ' ' '  

  • 8/16/2019 Understanding Forms in Drupal

    9/12

  • 8/16/2019 Understanding Forms in Drupal

    10/12

      $form['additionaldetails']['gender']=array( 

    '#type'=>'radios', 

    '#title'=>t('Gender'), 

    '#options'=>array('Male','Female') 

    ); 

    $form['additionaldetails']['suscribtion']=array( 

    '#type'=>'checkboxes', 

    '#title'=>t('I want to subscribe for'), 

    '#options'=>array('Email newsletter','Offer vouchers') 

    ); 

    $form['additionaldetails']['birthdate']=array( 

    '#type'=>'date', 

    '#title'=>t('Birthdate'), 

    ); 

    $form['#attributes']['enctype'] = 'multipart/form‐data';

      $form['additionaldetails']['picture']=array( 

    '#type'=>'file', '#title'=>t('Upload your picture'), 

    ); 

    $form['submit']=array( 

    '#type'=>'submit', 

    '#value'=>t('Submit') ); 

    return $form; 

    }

    This is what the new fieldsets look like:

  • 8/16/2019 Understanding Forms in Drupal

    11/12

    Conclusion

    Drupal helps you create and process forms right inside your module. The APIs Drupal offers make it very si

    to make an addition or modification of your form as the forms are arrays and even the validation and submi

    happens in a different function. This modular approach keeps the form code in your module clean and easy

    maintain. You also do not need to bother with the HTML details of the form if you use the Drupal form API –

    the HTML is auto-generated. Have fun creating your next form in your Drupal module!

    If you'd like us to cover a more specific use case or go into more details, or just have feedback, let us know i

  • 8/16/2019 Understanding Forms in Drupal

    12/12