You are here

function quiz_admin_add_question_ahah in Quiz 6.5

Same name and namespace in other branches
  1. 6.6 quiz.admin.inc \quiz_admin_add_question_ahah()
  2. 6.3 quiz.admin.inc \quiz_admin_add_question_ahah()

AHAH form completion for adding new questions.

1 string reference to 'quiz_admin_add_question_ahah'
quiz_menu in ./quiz.module
Implementation of hook_menu().

File

./quiz.admin.inc, line 446
Administrator interface for Quiz module.

Code

function quiz_admin_add_question_ahah() {
  $cached_form_state = array();
  $form_id = $_POST['form_build_id'];

  // Make sure the form exists
  if (!($cached_form = form_get_cache($form_id, $cached_form_state))) {
    form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
    $output = theme('status_messages');
    print drupal_to_js(array(
      'status' => TRUE,
      'data' => $output,
    ));
    exit;
  }

  // Just remember that $form_state is not checked, here. It's raw POST.
  $form_state = array(
    'values' => $_POST,
  );
  if (!empty($form_state['values']['always_autocomplete'])) {
    $new_question = $form_state['values']['always_autocomplete'];
    $frequency = 'always';
  }
  elseif (!empty($form_state['values']['random_autocomplete'])) {
    drupal_set_message('Adding random question', 'status');
    $new_question = $form_state['values']['random_autocomplete'];
    $frequency = 'random';
  }
  else {
    form_set_error('form_token', t('No question was found.'));
    $output = theme('status_messages');
    print drupal_to_js(array(
      'status' => TRUE,
      'data' => $output,
    ));
    exit;
  }
  $matches = array();
  $reg = '/id:([0-9]+)\\]$/';
  preg_match($reg, $new_question, $matches);

  // Modify the form to add a new entry to weights.
  if (!empty($matches[1]) && empty($cached_form['filtered_question_list_' . $frequency]['weights'][$frequency . '-' . $matches[1]])) {
    $cached_form['filtered_question_list_' . $frequency]['weights'][$frequency . '-' . $matches[1]] = array(
      '#type' => 'textfield',
      '#size' => 3,
      '#maxlength' => 4,
      '#default_value' => 0,
    );
  }

  // Re-save the cache.
  form_set_cache($form_id, $cached_form, $cached_form_state);

  // Because rendering a new table row is not possible from the server side, we
  // need to launch a one-time JavaScript to add the item to the table.
  $output = theme('status_messages') . '<script>Quiz.addQuestion("' . $frequency . '");</script>';
  print drupal_to_js(array(
    'status' => TRUE,
    'data' => $output,
  ));
  exit;
}