Form API Workflow - Updated to Drupal 5
Getting to know the workflow of forms in Drupal 5 took me a lot of time searching and trying, the differences with 4.7 are often only small.
So here's a story about how a form works in Drupal 5. This information will not be complete, more info can be found in the Forms API Quickstart Guide (http://api.drupal.org/api/5/file/developer/topics/forms_api.html) and the Drupal Form API. This is merely meant as a clarification to the workflow.
To add a form to the page you're building, you put in this code:
<?php
$page_content .= drupal_get_form('traveltrophy_form_newevent');
?>'traveltrophy_form_newevent' is the $form_id, and to build the form, Drupal looks for a function with the same name:
<?php
function traveltrophy_form_newevent() {
$form = array();
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('name'),
);
$form['distance'] = array(
'#type' => 'textfield',
'#title' => t('distance'),
);
$form['submit'] = array (
'#type' => 'submit',
'#value' => t('Go'),
);
return $form;
}
?>This is enough to build a form and display it on the screen. The different elements to be used in $form can be found in the Form API (http://api.drupal.org).
Remember that the $form_id was 'traveltrophy_form_newevent', so we need two more functions for the form to work: (_validate & _submit)
<?php
function traveltrophy_form_newevent_validate($form_id, $form_values) {
if ($form_values['name'] == '') {
form_set_error('', t('You have to put in a name'));
}
if (!is_numeric($form_values['distance'])) {
form_set_error('', t('The input for distance has to be a number'));
}
if ($form_values['distance'] == 0) {
form_set_error('', t('You have to fill in a distance'));
}
}
?>form_set_error(,) puts the form back as it was with the input the user just gave, and displays an error above it.
_submit is called if _validate did not return errors
<?php
function traveltrophy_form_newevent_submit($form_id, $form_values) {
if (user_access('moderate traveltrophy')) {
db_query("INSERT INTO reis_events VALUES (NULL , '%s', %d)", $form_values['name'], $form_values['distance']);
drupal_set_message(t('The input has been stored'));
}
return 'traveltrophy/listevent';
}
?>The return value is optional, it's the relative path to which the user is redirected after submission. If no return value is given, the current page is refreshed.
If you want to pass some variables to the form while building it, the drupal_get_form function can be called like this:
<?php
$page_content .= drupal_get_form('traveltrophy_form_newevent',$id,$whatever,..);
?>And gives input to:
<?php
function traveltrophy_form_newevent($id,$whatever,..) {
$form = array();
//..
}
?>