Drupal's Form API is powerful, but it's associated learning curve can be a steep one.  However, if you stick to these basic 5 steps you will be off to a good start in creating your own Drupal theme on the double.

The 5 basic steps to create a Drupal form using the API are as follows:

 

  1. A menu item
  2. A menu callback for that menu item
  3. Define the form
  4. Validate the form
  5. Re-direct or post-validation form submission

This document doesn't go into the basics of creating a module, but assues that you already possess that knowledge or can use Google.  This module is called basicform!

<?php
//  $Id$

/**
 * Implementation of hook_menu().    STEP 1
 */
function basicform_menu() {
    $items['basicform'] = array(
        'title' => 'View the form',
        'page callback' => 'basicform_page',
        'access arguments' => array('access content'),
    );
    return $items;
}

/**
 * Menu callback.                   STEP 2
 * Called when user goes to http://yourIP/?q=basicform
 */
function basicform_page() {
    $output = t('This page contains our example form.');

    //  Return the HTML generated from the $form data structure.
    $output .=drupal_get_form('basicform_nameform');
    return $output;
}

/**
 * Define a form                     STEP 3 
*/
function basicform_nameform() {

    // User_name Form Element
    $form['user_name'] = array(
        '#title' => t('Your Name'),
       '#type' => 'textfield',
       '#description' => t('Enter your desired name.'),
    );
    // Submit Form Element
   $form['submit'] = array(
       '#type' => 'submit',
        '#value' => t('Submit')
   );
    return $form;
}

/**
 * Validate the form          STEP 4
 */
function basicform_nameform_validate($form, &$form_state) {

    if ($form_state['values']['user_name'] == 'Duddly') {
        // Set a message that the user_name has failed

        form_set_error('user_name',
                t('Duddly is not allowed to use this form.'));
    }
}

/**
 * Post-validation form submission.          STEP 5
 */
function basicform_nameform_submit($form, &$form_state)   {
    $name = $form_state['values']['user_name'];
    // tell Drupal to set a message for the user
    drupal_set_message(t('Good on ya, %name',
            array('%name' => $name)));
}


 And off to the races you go if you stick to these five basic steps. 

 

0
Your rating: None
Navigation
Syndicate
Syndicate content
Share this
Powered by Drupal, an open source content management system