我正在尝试学习编写drupal模块并正在编写一个简单的数学模块http://nodeone.se/en/the-math-question-module
我的 GUI 很好,但实际数学似乎有问题。我似乎从来没有得到正确的答案,因为我认为它会在检查当前答案之前加载一组新问题。
这是我到目前为止所拥有的:
<?php
/**
* @file
* Tests users on their math skills through a series of question and answers
*/
/**
* Implements hook_menu().
*/
function math_question_menu() {
// add new navigation menu item
$items['math_question'] = array(
'title' => 'Math questions',
'description' => 'Test you math skills with these questions.',
'page callback' => 'drupal_get_form',
'page arguments' => array('math_question_page'),
'access callback' => 'user_access',
'access arguments' => array('administer_site_configuration'),
);
return $items;
}
$val1 = rand(1,10);
$val2 = rand(1,10);
variable_set('val1', $val1);
variable_set('val2', $val2);
/**
* Builds the form for configuring Math Questions.
*/
function math_question_page() {
global $user;
$num1 = variable_get('val1');
$num2 = variable_get('val2');
$total = $num1 + $num2;
variable_set('total',$total);
$form['math_question'] = array(
'#type' => 'item',
'#markup' => 'What is ' . $num1 . ' + ' . $num2 . ', ' .
check_plain($user->name) . '?',
);
$form['answer'] = array(
'#type' => 'textfield',
'#title' => t('Answer'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Check my answer'),
);
return $form;
}
function math_question_page_validate($form, $form_state) {
if (empty($form['answer']['#value'])) {
form_error($form['answer'], t('This field is required.'));
}
if ($form['answer']['#value'] ==
variable_get('total')) {
$msg = t('Good job!');
$type = 'status';
}
else {
$msg = t('Try again...');
$type = 'error';
}
drupal_set_message(check_plain($msg), $type);
}
修改代码:。.
/**
* Builds the form for configuring Math Questions.
*/
function math_question_page() {
global $user;
$val1 = rand(1,10);
$val2 = rand(1,10);
$total = $val1 + $val2;
$form['math_question'] = array(
'#type' => 'item',
'#markup' => 'What is ' . $val1 . ' + ' . $val2 . ', ' .
check_plain($user->name) . '?',
);
$form['answer'] = array(
'#type' => 'textfield',
'#title' => t('Answer'),
);
$form['total'] = array(
'#type' => 'hidden',
'#value' => $total,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Check my answer'),
);
return $form;
}
function math_question_page_validate($form, $form_state) {
if (empty($form['answer']['#value'])) {
form_error($form['answer'], t('This field is required.'));
}
if ($form['answer']['#value'] ==
$form['total']['#value']) {
$msg = t('Good job!');
$type = 'status';
}
else {
$msg = t('Try again...');
$type = 'error';
}
drupal_set_message(check_plain($msg), $type);
}