验证用户提交的设置

  如果由函数system_settings_form()为我们负责保存表单数值,那么我们如何才能判定在“Annotations per node”字段中输入的是一个数字?我们可以钩住表单提交的处理过程么?当然可以了。我们只需在sites/all/modules/custom/annotate/annotate.admin.inc中定义一个验证函数,如果我们发现有任何异常的话,就使用这个函数来设置一个错误消息。

 
/**
* Validate the annotation configuration form.
*/
function annotate_admin_settings_validate($form, $form_state) {
    $limit = $form_state['values']['annotate_limit_per_node'];
    if (!is_numeric($limit)) {
        form_set_error('annotate_limit_per_node', t('Please enter a number.'));
    }
}
 
    现在,当Drupal处理这个表单时,它将回调annotate_admin_settings_validate()来进行验证。如果我们检测到输入了无效数据的话,那么我们将为发生错误的字段设置一个错误信息,这反映为在页面上就是显示一个警告信息,并将包含错误的字段进行高亮显示,如图2-5所示:
图2-5 验证脚本设置了一个错误信息
 
    Drupal是怎么知道要调用我们的函数呢?我们对函数的命名采用了特殊的方式,使用表单定义函数的名字(annotate_admin_settings)+ _validate。对于Drupal是如何判定要调用哪个验证函数的详细解释,可参看第10章。
 
 老葛的Drupal培训班 Think in Drupal

Drupal版本: