Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In the validation function <code>math_question_page_validate()</code>, you should access the values from $form_state variable, not from $form.</p> <p>eg: </p> <pre><code>if (!$form_state['values']['answer'] == $form_state['values']['total']) { form_set_error('answer', $error); } </code></pre> <p><del>You can also store the answer in $form_state variable to pass it to the validation function (no need to store the value in $form). if you store it as $form_state['total'], you can access it in the same way (given below).</del></p> <p><del>if (!$form_state['total'] == $form_state['values']['answer']) {form_set_error('answer', $error);}</del></p> <p>Thank you very much <a href="https://stackoverflow.com/users/1277693/papirrin">papirrin</a> for teaching <a href="https://stackoverflow.com/a/15308905/1767085">this</a>.</p> <p>I suggest to use variable_get() to keep the correct answer safe. The random value you keep in the form will not survive the form regeneration. </p> <p>My working code here.</p> <pre><code>/** * Builds the form for configuring Math Questions. */ function math_question_page($form, &amp;$form_state) { global $user; $val1 = rand(1,10); $val2 = rand(1,10); $total = $val1 + $val2; // Store the correct answer safely away from this form if (!variable_get('math_question_answer',FALSE)) { variable_set('math_question_answer', $total); } $form['math_question'] = array( '#type' =&gt; 'item', '#markup' =&gt; 'What is ' . $val1 . ' + ' . $val2 . ', ' . check_plain($user-&gt;name) . '?', ); $form['answer'] = array( '#type' =&gt; 'textfield', '#title' =&gt; t('Answer'), ); $form['submit'] = array( '#type' =&gt; 'submit', '#value' =&gt; t('Check my answer'), ); $form_state['redirect'] = FALSE; return $form; } function math_question_page_submit($form, &amp;$form_state) { if (empty($form['answer']['#value'])) { form_set_error('answer', t('This field is required.')); } else { if ($form_state['values']['answer'] == variable_get('math_question_answer')) { $msg = t('Good job!'); $type = 'status'; } else { $msg = t('Try again...'); $type = 'error'; } drupal_set_message(check_plain($msg), $type); } variable_del('math_question_answer'); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload