30 Seconds on the Drupal Form API

It's pretty easy to forget all the details of the Drupal Forms API, so we'll stop for a minute for a very short review.

(This one is at ahah_demo/simple_form.)

You add a form to your page like this:

<?php
$output
.= drupal_get_form('ahah_demo_simplest_form');
?>

Often that's done right from the hook_menu implementation.

The layout of a form is as below:

<?php
/**
 * A Hello-world for Forms API (FAPI)
 */
function ajax_demo_simplest_form($form, &$form_state) {

 
$form['explanation'] = array(
   
'#type' => 'markup',
   
'#value' => '<div>' . t('This is a basic form with just a bit of information') . '</div>',
  );

 
$form['experience'] = array(
   
'#type' => 'select',
   
'#title' => t('What is your experience level in Drupal?'),
   
'#options' => array(
     
'expert' => t('Expert'),
     
'journeyman' => t('Journeyman'),
     
'beginner' => t('Beginner')),
  );
 
$form['more'] = array(
   
'#type' => 'textfield',
   
'#title' => t("Say more about yourself"),
   
'#description' => t('Surely one word can\'t describe you.'),
  );
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Click Me'),
  );

  return
$form;
}


function
ajax_demo_simplest_form_submit($form, &$form_state) {
 
drupal_set_message(t('You have claimed to be %experience: %more',
    array(
     
'%experience'=>$form_state['values']['experience'],
     
'%more' => $form_state['values']['more'],
    )
  ));
}
?>

Topics: 

1 Comment

Just the info I needed!

Drupal 7 forms in plain English! This is just the quick start I needed. It clicked. Life is good now.

Thanks a ton!

Best regards,

Chris