从验证函数中传递数据

老葛的Drupal培训班 Think in Drupal

从验证函数中传递数据
    如果你的验证函数做了大量的处理,而你又想把结果保存下来以供提交函数使用,那么有两种不同的方式。你可以使用form_set_value()或者使用$form_state。
 
使用form_set_value()传递数据
最正式的方式是,当你在表单定义函数中创建表单时,创建一个表单元素来隐藏该数据,然后使用form_set_value()存储该数据。首先,你需要创建一个用来占位的表单元素:
 
$form['my_placeholder'] = array(
    '#type' => 'value',
    '#value' => array()
);
接着,在你的验证程序中,你把数据保存起来:
 
// Lots of work here to generate $my_data as part of validation.
...
// Now save our work.
form_set_value($form['my_placeholder'], $my_data, $form_state);
 
然后你就可以在提交函数中访问该数据了:
 
// Instead of repeating the work we did in the validation function,
// we can just use the data that we stored.
$my_data = $form_values['my_placeholder'];
 
或者假定你想将数据转化为标准形式。例如,你在数据库中存有一列国家代码,你需要对它们进行验证,但是你的不讲道理的老板坚持----用户可以在文本输入框中键入国家名称。你需要在你的表单中创建一个占位表单元素,通过使用一种巧妙的方式对用户输入进行验证,这样你就可以同时将“The Netherlands”和 “Nederland”映射为ISO 3166 国家代码“NL”了。
 
$form['country'] = array(
    '#title' => t('Country'),
    '#type' => 'textfield',
    '#description' => t('Enter your country.')
);
 
// Create a placeholder. Will be filled in during validation.
$form['country_code'] = array(
    '#type' => 'value',
    '#value' => ''
);
在验证函数内部,你将国家代码保存到占位表单元素中:
 
// Find out if we have a match.
$country_code = formexample_find_country_code($form_state['values']['country']);
if ($country_code) {
    // Found one. Save it so that the submit handler can see it.
    form_set_value($form['country_code'], $country_code, $form_state);
}
else {
    form_set_error('country', t('Your country was not recognized. Please use
        a standard name or country code.'));
}
 
    现在,提交处理器就可以使用$form_state['values'] ['country_code']访问国家代码了。

Drupal版本: