我正在为我的一个客户开发简单的留言簿模块,为了防止垃圾邮件,我决定使用一系列简单的问题。为此,我必须从数组中选择随机问题并在表单中设置此问题的 ID(数组元素 ID),以便我可以在提交处理程序中检查答案。问题是在评估提交处理程序之前重新生成表单,因此随机值会发生变化。
很快:我$form_state['values']['queston_id']
在提交处理程序函数中得到了其他值,它是形式的。为什么会这样,我该如何改变?
非常感谢!
这是我的模块:
function gb_menu() {
$items = array();
$items['gb'] = array(
'title' => t('Guestbook'),
'description' => t('Guestbook page'),
'page callback' => 'gb_guestbook',
//'page arguments' => array('gb_guestbook'),
'access arguments' => array('view guestbook'),
);
return $items;
}
function gb_guestbook() {
dpm('generating page');
$page = NULL;
$page .= drupal_render(drupal_get_form('gb_guestbook_form'));
$page .= 'list of guestbook messages here';
return $page;
}
function gb_guestbook_form($form, &$form_state) {
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#description' => t('Please, enter your name.'),
);
$form['message'] = array(
'#type' => 'textarea',
'#cols' => 5,
'#title' => t('Message'),
'#description' => t('Please, enter your message.'),
);
$questions = gb_get_question();
$question_id = rand(0, count($questions)-1);
$question = $questions[$question_id];
$form['question_id'] = array(
'#type' => 'hidden',
'#value' => $question_id,
);
$form['spam'] = array(
'#title' => $question['question'],
'#description' => t('Please, answer the simple question so we know that you are a human.'),
'#type' => 'textfield',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function gb_guestbook_form_submit($form, &$form_state) {
// spam check
$values = $form_state['values'];
$questions = gb_get_question();
$answers = $questions[$values['question_id']]['answers'];
if (!in_array(strtolower($values['spam']), $answers)) {
drupal_set_message(t('You did not reply the answer correctly. Are you sure it was not typo?'), 'error');
}
else {
drupal_set_message(t('Thanks for the contribution!'), 'status');
// processing input
}
}
function gb_get_question() {
return array(
array (
'question' => t('What is the capital of Slovakia?'),
'answers' => array('bratislava'),
),
array (
'question' => t('What is the name of this band?'),
'answers'=> array('divozel'),
),
array (
'question' => t('What is the biggest town in east part of Slovakia?'),
'answers' => array('košice','kosice'),
),
);
}