You are here

function QuizResultController::save in Quiz 7.6

Same name and namespace in other branches
  1. 7.5 includes/QuizResultController.class.inc \QuizResultController::save()

Save the Quiz result and do any post-processing to the result.

Parameters

type $entity:

\DatabaseTransaction $transaction:

Return value

boolean

Overrides EntityAPIController::save

File

includes/QuizResultController.class.inc, line 73

Class

QuizResultController

Code

function save($entity, \DatabaseTransaction $transaction = NULL) {
  if (empty($entity->time_start)) {
    $entity->time_start = REQUEST_TIME;
  }
  $new = !empty($entity->is_new);

  // Save the Quiz result.
  parent::save($entity, $transaction);

  // Post process the result.
  if ($new) {
    $quiz = node_load($entity->nid, $entity->vid);

    // Call @deprecated hook_quiz_begin().
    module_invoke_all('quiz_begin', $quiz, $entity->result_id);

    // Create question list.
    $questions = quiz_build_question_list($quiz);
    if ($questions === FALSE) {
      drupal_set_message(t('Not enough random questions were found. Please add more questions before trying to take this @quiz.', array(
        '@quiz' => QUIZ_NAME,
      )), 'error');
      return FALSE;
    }
    if (count($questions) == 0) {
      drupal_set_message(t('No questions were found. Please !assign_questions before trying to take this @quiz.', array(
        '@quiz' => QUIZ_NAME,
        '!assign_questions' => l(t('assign questions'), 'node/' . $quiz->nid . '/quiz/questions'),
      )), 'error');
      return FALSE;
    }
    $i = 0;
    foreach ($questions as $question) {
      $quiz_result_answer = entity_create('quiz_result_answer', array(
        'result_id' => $entity->result_id,
        'question_nid' => $question['nid'],
        'question_vid' => $question['vid'],
        'tid' => !empty($question['tid']) ? $question['tid'] : NULL,
        'number' => ++$i,
      ));
      entity_save('quiz_result_answer', $quiz_result_answer);
    }
    if (!empty($entity->build_on_last)) {
      $build_on_last = $entity->build_on_last;

      // @kludge we need to reload to get the layout loaded on.
      $entity = quiz_result_load($entity->result_id);
      $entity->build_on_last = $build_on_last;

      // Build on the last attempt the user took. If this quiz has build on last
      // attempt set, we need to search for a previous attempt with the same
      // version of the current quiz.
      $quiz_result_old = self::findOldResult($entity);

      // Now clone the answers on top of the new result.
      quiz_clone_quiz_result($quiz_result_old, $entity);
    }
  }
}