【问题标题】:How to access form data in hook_form_validate() in drupal 7如何在 drupal 7 的 hook_form_validate() 中访问表单数据
【发布时间】:2011-11-24 06:16:14
【问题描述】:

我有一个从 hook_form 实现的名为 simplequiz_form() 的表单我想在提交后访问它的数据 下面是我编写的代码,但是一旦提交,我似乎无法访问它的数据。我做错了什么?

function simplequiz_form_validate($form, &$form_state) {
// here  is where we will validate the data and save  it in the db.
$thid = db_insert('simplequiz')
->fields(array(

'questions' => &$form_state['question'],
**I can't seem to access the value of a field questions** 

))
->execute();

 return $thid;
 }

下面是我的 hook_form() 实现

function simplequiz_form($form, &$form_submit)
{ 

$form['question'] = array(
'#title' => t('Please input your question'),
'#type' => 'text_format',
'#required' => FALSE,
'#description' => t('Here is where you can enter your questions'),    
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;

}

如果我使用 $form_state['values']['question']

我收到以下错误:

PDOException:SQLSTATE[21S01]:插入值列表与列列表不匹配:1136 列计数与第 1 行的值计数不匹配:INSERT INTO {simplequiz}(问题)值(:db_insert_placeholder_0_value,:db_insert_placeholder_0_format ); simplequiz_form_submit() 中的数组( [:db_insert_placeholder_0_value] => [:db_insert_placeholder_0_format] => filtered_html )(/home/vishal/Dropbox/sites/dev/sites/all/modules/simplequiz/simplequiz.module 的第 245 行)。强>

它使用 $form_state['values']['question']['value']

【问题讨论】:

    标签: drupal drupal-7 drupal-modules


    【解决方案1】:

    使用hook_form_validate 是最佳实践,仅用于验证目的,除了验证之外的任何操作都应在hook_form_submit 中完成。

    无论哪种方式,它们的功能都几乎相同。

    所有表单数据都存储在$form_state['values']中,所以要访问$form['questions']的值,只需使用$form_state['values']['questions']即可。

    【讨论】:

    • 它工作了我不得不稍微改变一下 $form_state['values']['question']['value']
    • 只是备注:没有 hook_form_validate()。这称为“表单验证处理程序”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多