Form API Tip: Use form_set_value() to change form values during validation
Using Drupal's form api can often times make form validation and submission handling simple and effective. Today's tip is about using the form_set_value($form, $value) function to change a form item's value during the validation phase. This is convenient if you've done any manipulation to the submitted data during the validation process and you don't want to have to redo it in the submit process.
For those of you with the Pro Drupal Development book like myself there is an example of how to use this feature of the form api on page 163-165, however some small but important details were left out.
The key to getting this handy feature to work is to define your hook_validate function with a third parameter, I used $form.
The following is obviously not a complete implementation of a form, but the necessary elements can be seen. Notice that I have two fields, one of which is going to be our place holder ('myitem') and the other which actually takes the user input. During validation I process the user input variable and store it in the place holder. This allows me to access the manipulated value in our submit process through the place holder variable.
function myform() {
$form['input'] = array(
'#type' => 'textfield',
'#title' => t('User Input'),
);
$form['myitem'] = array(
'#type' => 'value',
'#value' => array(),
);
return $form;
}
function myform_validate($form_id, $form_values, $form) {
form_set_value($form['myitem'], strtolower($form_values['input']);
}
function myform_submit($form_id, $form_values) {
// access our manipulated input at $form_values['myitem']
}

Delicious
Digg
StumbleUpon
Propeller
Reddit
Magnoliacom
Newsvine
Furl
Facebook
Google
Yahoo
Technorati
Icerocket
Post new comment