老葛的Drupal培训班 Think in Drupal
接下来,我们把实际的模块放在sites/all/modules/custom/formexample/formexample.module:
<?php
// $Id$
/**
* @file
* Play with the Form API.
*/
/**
* Implementation of hook_menu().
*/
function formexample_menu() {
$items['formexample'] = array(
'title' => 'View the form',
'page callback' => 'formexample_page',
'access arguments' => array('access content'),
);
return $items;
}
/**
* Menu callback.
*/
function formexample_page() {
$output = t('This page contains our example form.');
// Return the HTML generated from the $form data structure.
$output .= drupal_get_form('formexample_nameform');
return $output;
}
/**
* Define a form.
*/
function formexample_nameform() {
$form['user_name'] = array(
'#title' => t('Your Name'),
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}
/**
* Validate the form.
*/
function formexample_nameform_validate($form, &$form_state) {
if ($form_state['values']['user_name'] == 'King Kong') {
// We notify the form API that this field has failed validation.
form_set_error('user_name',
t('King Kong is not allowed to use this form.'));
}
}
/**
* Handle post-validation form submission.
*/
function formexample_nameform_submit($form, &$form_state) {
$name = $form_state['values']['user_name'];
drupal_set_message(t('Thanks for filling out the form, %name',
array('%name' => $name)));
}