Drupal 7: how to create a form within a module

Drupal If you develop modules and you need to create a form in one of your page, there is a nice Drupal function that can render an array into a pretty HTML form: drupal_get_form().

This handy function is usually needed in a menu callback as it does not require an existing form.

You can use it like this:

/**
 * Implements hook_menu()
 */
function mymodule_menu() {
 $items['mymodule'] = array(
  'title' => 'My title', //The name of the menu that will be displayed
  'page callback' => 'mymodule_page_callback', //The name of the function that will output a page
 );
 return $items;
}

function mymodule_page_callback() {
 //The argument is the name of the function with the form details
 return drupal_get_form('mymodule_form');
}

function mymodule_form($form, &$form_state) {
 $form = array (
  //The action attribute of the HTML form tag
  '#action' => '#', 
  //We define a simple text field for the "name"
  'name' => array ( 
   '#type' => 'textfield',
   //The label that will be placed with the field
   '#title' => t('My pretty name'),
   //The description will be placed right below the field
   '#description' => t('My descrition'),
   //If true the system will perform a simple check on submit so that it is never empty
   '#required' => TRUE,
  ),
  //We define a simple submit button
  'submit' => array ( 
   '#type' => 'submit',
   '#value' => t('My submit'),
  ),
 );
 
 return $form;
}

After you have defined the form, you can implement 2 extra functions that will handle the validation (_validate) and the processing (_submit) of the form values.

function mymodule_form_validate($form, &$form_state){
 // My validation parameters
 if(strlen($form_state['values']['name']) > 10) {
  form_set_error('', t('Hey, your name is too long!'));
 }
}

function mymodule_form_submit($form, &$form_state) {
 //My success processing
 drupal_set_message(t('Yay, your name is fine!'));
}

And that is, pretty simple uh?

2013 10 10 Edit: Updated with the syntax highlighter!

Advertisements

16 thoughts on “Drupal 7: how to create a form within a module

  1. Hello sir,
    Can please put the code for editing and deleting the form submissions also. Or please explain how to do that

    thanks

    • Hello Tushar,
      thank you for your question, the answer is not easy, it depends on the logic you implement in the _submit function.

      Depending on how you save the information you gather you will have one or more ways to delete or edit your entities, you could for instance handle the submissions with a custom view that will serve as administrative panel.

      I believe you could also implement your custom functions to edit and delete the data using entity queries.

      • Thanks for the reply soraph,
        I am actually pushing the data into database in a custom table created by hook_schema. Here is mine .install file

        ‘First Table for form example by tushar’,
        ‘fields’ => array(
        ‘fe_id’ => array(
        ‘description’ => ‘The primary identifier for a form example.’,
        ‘type’ => ‘serial’,
        ‘unsigned’ => TRUE,
        ‘not null’ => TRUE,
        ),
        ‘mynumber’ => array(
        ‘description’ => ‘Field for storing an interger’,
        ‘type’ => ‘int’,
        ‘unsigned’ => TRUE,
        ‘not null’ => TRUE,
        ‘default’ => 0,
        ),
        ‘mytextfield’ => array(
        ‘description’ => ‘Text field for short tags’,
        ‘type’ => ‘varchar’,
        ‘length’ => 50,
        ‘not null’ => TRUE,
        ‘default’ => ”,
        ),
        ‘mytext’ => array(
        ‘description’ => ‘Field for storing bigger string’,
        ‘type’ => ‘text’,
        ‘not null’ => TRUE,
        ),
        ),
        ‘indexes’ => array(
        ‘form_example_mynumber’ => array(‘mynumber’),
        ),
        ‘primary key’ => array(‘fe_id’),
        );
        return $schema;
        }
        ?>

        And this is my .module file

        array(
        ‘title’ => t(‘Submit form_example’),
        ‘description’ => t(‘submit the form_example form.’),
        ),
        ‘access form_example submissions’ => array(
        ‘title’ => t(‘Access form_example Submission’),
        ‘description’ => t(‘Who can access the form_example submissions?’),
        ),
        );
        }

        /**
        * Implements hook_menu().
        */
        function form_example_menu() {
        $items[‘form-example’] = array(
        ‘title’ => ‘Form Example’,
        ‘type’ => MENU_NORMAL_ITEM,
        ‘page callback’ => ‘drupal_get_form’,
        ‘page arguments’ => array(‘form_example_form’),
        ‘access arguments’ => array(‘submit form_example’),
        );
        $items[‘form-submissions’] = array(
        ‘title’ => ‘Form Example Submissions’,
        ‘type’ => MENU_NORMAL_ITEM,
        ‘page callback’ => ‘form_example_submissions’,
        ‘access arguments’ => array(‘access form_example submissions’),
        );
        return $items;
        }

        /**
        * My Example form page
        */
        function form_example_form($form, &$form_state) {

        $form[‘mynumber’] = array(
        ‘#type’ => ‘textfield’,
        ‘#title’ => t(‘My Number’),
        ‘#size’ => 10,
        ‘#maxlength’ => 10,
        ‘#required’ => TRUE,
        ‘#description’ => t(‘Enter any interger number’),
        );

        $form[‘mytextfield’] = array(
        ‘#type’ => ‘textfield’,
        ‘#title’ => t(‘My Text Field’),
        ‘#size’ => 60,
        ‘#maxlength’ => 128,
        ‘#required’ => TRUE,
        );

        $form[‘mytext’] = array(
        ‘#type’ => ‘textarea’,
        ‘#title’ => t(‘My Text-Area’),
        ‘#description’ => t(‘Enter some text’),
        ‘#required’ => TRUE,
        );

        $form[‘submit’] = array(
        ‘#type’ => ‘submit’,
        ‘#value’ => t(‘Add Item’),
        );

        return $form;
        }

        /**
        * Validation handler for form_example
        */
        function form_example_form_validate ($form, &$form_state) {

        //debug code!!
        //print(‘

        '.print_r($form_state['values'],1).'

        ‘); die();

        if(!is_numeric($form_state[‘values’][‘mynumber’])) {
        form_set_error(‘mynumber’, t(‘Ginti nhi aati kya?’));
        return FALSE;
        }
        return TRUE;
        }

        /**
        * Submission handler for form_example -> Insert into database
        */
        function form_example_form_submit($form, &$form_state) {
        $fe_id = db_insert(‘form_example’)
        ->fields(array(
        ‘mynumber’ => $form_state[‘values’][‘mynumber’],
        ‘mytextfield’ => $form_state[‘values’][‘mytextfield’],
        ‘mytext’ => $form_state[‘values’][‘mytext’],
        ))
        ->execute();

        drupal_set_message(t(‘HO GYA Submit!!!!’));
        }

        /**
        * View Submissions by form_example
        */
        function form_example_submissions() {
        $results = db_query(“SELECT * FROM {form_example}”);

        $header = array(t(‘ID’), t(‘My Number’), t(‘My Text Field’), t(‘My Text’));

        $rows = array();

        foreach($results AS $result) {
        //print(‘

        '.print_r($result,1).'

        ‘);
        $rows[] = array(
        check_plain($result->fe_id),
        check_plain($result->mynumber),
        check_plain($result->mytextfield),
        check_plain($result->mytext),
        );
        }
        $link_to_add_form = l(‘Add More’,’form-example’);
        return theme(‘table’, array(‘header’ => $header, ‘rows’ => $rows)).”.$link_to_add_form;
        }
        ?>

      • This will be clear now:-

        .install file

        <?php 
        
        /**
         * Implements hook_schema().
         */
        function form_example_schema() {
          
          $schema = array();
          	
          $schema['form_example'] = array(
          
            'description' => 'First Table for form example by tushar',
            'fields' => array(
              'fe_id' => array(
                'description' => 'The primary identifier for a form example.',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
              ),
              'mynumber' => array(
                'description' => 'Field for storing an interger',
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
              ),
              'mytextfield' => array(
                'description' => 'Text field for short tags',
                'type' => 'varchar',
                'length' => 50,
                'not null' => TRUE,
                'default' => '',
              ),
              'mytext' => array(
                'description' => 'Field for storing bigger string',
                'type' => 'text',
                'not null' => TRUE, 
              ),
            ),
            'indexes' => array(
              'form_example_mynumber' => array('mynumber'),
            ),
            'primary key' => array('fe_id'),
          );
          return $schema;
        }
        ?>
        

        .module file

        <?php
        
        /**
         * Implements hook_permission().
         */
        function form_example_permission() {
          return array(
            'submit form_example' => array(
              'title' => t('Submit form_example'),
              'description' => t('submit the form_example form.'),
            ),
            'access form_example submissions' => array(
              'title' => t('Access form_example Submission'),
              'description' => t('Who can access the form_example submissions?'),
            ),
          );
        }
        
        /**
         * Implements hook_menu().
         */
        function form_example_menu() {
          $items['form-example'] = array(
            'title' => 'Form Example',
            'type' => MENU_NORMAL_ITEM,
            'page callback' => 'drupal_get_form',
            'page arguments' => array('form_example_form'),
            'access arguments' => array('submit form_example'),
          );
          $items['form-submissions'] = array(
            'title' => 'Form Example Submissions',
            'type' => MENU_NORMAL_ITEM,
            'page callback' => 'form_example_submissions',
            'access arguments' => array('access form_example submissions'),
          );
          return $items;
        }
        
        /**
         * My Example form page
         */
        function form_example_form($form, &$form_state) {
          
          $form['mynumber'] = array(
            '#type' => 'textfield',
            '#title' => t('My Number'),
            '#size' => 10,
            '#maxlength' => 10,
            '#required' => TRUE,
            '#description' => t('Enter any interger number'),
          );
          
          $form['mytextfield'] = array(
            '#type' => 'textfield',
            '#title' => t('My Text Field'),
            '#size' => 60,
            '#maxlength' => 128,
            '#required' => TRUE,
          );
          
          $form['mytext'] = array(
            '#type' => 'textarea',
            '#title' => t('My Text-Area'),
            '#description' => t('Enter some text'),
            '#required' => TRUE,
          );
          
          $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Add Item'),
          );
          
          return $form;
        }
        
        /**
         * Validation handler for form_example
         */
        function form_example_form_validate ($form, &$form_state) {
          
          //debug code!!
          //print('<pre>'.print_r($form_state['values'],1).'</pre>'); die();
          
          if(!is_numeric($form_state['values']['mynumber'])) {
            form_set_error('mynumber', t('Ginti nhi aati kya?'));
            return FALSE;
          }
          return TRUE;
        }
        
        /**
         * Submission handler for form_example -> Insert into database
         */
        function form_example_form_submit($form, &$form_state) {
          $fe_id = db_insert('form_example')
            ->fields(array(
              'mynumber' => $form_state['values']['mynumber'],
              'mytextfield' => $form_state['values']['mytextfield'],
              'mytext' => $form_state['values']['mytext'],
            ))
            ->execute();
          
          drupal_set_message(t('HO GYA Submit!!!!'));  
        }
        
        /**
         *  View Submissions by form_example
         */
        function form_example_submissions() {
          $results = db_query("SELECT * FROM {form_example}");
          
          $header = array(t('ID'), t('My Number'), t('My Text Field'), t('My Text'));
          
          $rows = array();
          
          foreach($results AS $result) {
            //print('<pre>'.print_r($result,1).'</pre>');
            $rows[] = array(
              check_plain($result->fe_id),
              check_plain($result->mynumber),
              check_plain($result->mytextfield),
              check_plain($result->mytext),
            );
          }
          $link_to_add_form = l('Add More','form-example');
          return theme('table', array('header' => $header, 'rows' => $rows)).'<br>'.$link_to_add_form;
        }
        ?>
        
      • Yes that I know, but I am not able to figure out how to send my primary key value and based on that update it. Even I am not able to figure out of how to add an edit button in it.

      • I never did something like that, but looking at your code in the form_example_submissions() you could output a string that will call a specific URL that will be handled by your module implementing a hook_menu() to map a page where you will load the record and then allow the user to edit or delete it. In theory it should work, I used something like that in several modules, but never to edit or delete records in a custom table, I always used Drupal’s content types to avoid doing that.

      • Yes Soraph this is what I am asking for. Can you please share some demo code to do that. I am actually a beginner in Drupal module development.

      • Soraph, can you please tell me how can I insert a delete button in my “Form Example Submissions” function name is – “function form_example_submissions()”

  2. And to theme the form:


    function mymodule_form($form, &$form_state) {
    ...
    $form['#theme'] = 'mymodule_theme';
    return $form;
    }

    function theme_mymodule_theme($variables) {
    $form = $variables['form'];
    $buildform = '' . drupal_render($form['element1']) . '';
    $buildform .= drupal_render($form['element2']);
    $buildform .= drupal_render($form['form_build_id']);
    $buildform .= drupal_render($form['form_id']);
    $buildform .= drupal_render($form['form_token']);
    $form['element']['#children'] = $buildform;
    $output = theme_form($form);
    return $output;
    }

Your opinion is important!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s