This screencast shows some more aspects of form API, namely how to write functions that are called when forms are submitted. It also includes how to set default values for form elements. In more detail, this screencast includes:
- That functions named FORM_ID_submit($form, $form_state) will by default be called on form submissin
- That data storing should NOT be done by the form submit function, but by a separate function (since data handling should be possible to do without any forms)
- That submitted values can be found in $form_state['input']
- The two functions variable_set and variable_get, used for storing simple and small variables
- That the property #defaule_value can be used to set default values for form elements
- An example of how to use the implode() and explode() functions to manage line breaks
code added/changed in wordlist.module
/**
* Builds the form for configuring Word list.
*/
function wordlist_page() {
$form['wordlist_words'] = array(
'#type' => 'textarea',
'#title' => t('Words to inlcude in the list'),
'#description' => t('The words included in this list will be available to Rules and other modules making use of the global "site" entity.'),
'#default_value' => implode("\r\n", variable_get('wordlist_words', array())),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save')
);
return $form;
}
/**
* Submit function for the Word list configuration page.
*/
function wordlist_page_submit($form, $form_state) {
// Break up the list of words according to line breaks.
$words = explode("\r\n", $form_state['input']['wordlist_words']);
wordlist_save_list($words);
drupal_set_message(t('The words have been saved!'));
}
/**
* Stores the globally accessible Word list words.
* @param $words
* An array containing the words that should be stored.
*/
function wordlist_save_list(array $words) {
variable_set('wordlist_words', $words);
}
Comments
Patrick
January 24, 2012I love your screencasts! They are a great help to me as I learn more about Drupal. I'd just like to let you know that the RSS link at the top of the learning library is broken. I would have made this comment privately but I couldn't find an appropriate place to do so.
Johan Falk
January 25, 2012 Thanks! Forwarding it to the team taking care of the site.