You are here

function quiz_views_pre_view in Quiz 6.x

Same name and namespace in other branches
  1. 8.6 includes/views/quiz.views.inc \quiz_views_pre_view()
  2. 8.5 includes/views/quiz.views.inc \quiz_views_pre_view()
  3. 7.5 includes/views/quiz.views.inc \quiz_views_pre_view()

Implements hook_views_pre_view().

Replace the static field with dynamic fields.

@todo this only works on a single quiz, with the first argument being a quiz ID (e.g. quiz/1/results). Should be expanded to make argument configurable.

File

./quiz.module, line 604
Contains quiz.module

Code

function quiz_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $fields = $view
    ->getHandlers('field');
  foreach ($fields as $field_name => $field) {
    if ($field['id'] == 'quiz_result_answers') {
      $quiz = Drupal::service('entity_type.manager')
        ->getStorage('quiz')
        ->load($args[0]);
      $i = 0;
      foreach ($quiz
        ->getQuestions() as $quizQuestionRelationship) {
        $quizQuestion = $quizQuestionRelationship
          ->getQuestion();
        if ($quizQuestion
          ->isGraded()) {
          $i++;
          $newfield = [];
          $newfield['id'] = 'quiz_result_answer';
          $newfield['field'] = 'quiz_result_answer';
          $newfield['table'] = 'quiz_result';
          $newfield['alter'] = [];
          $newfield['label'] = t('@num. @question', [
            '@num' => $i,
            '@question' => $quizQuestion
              ->get('title')->value,
          ]);
          $newfield['qqid'] = $quizQuestion
            ->id();
          $newfield['entity_type'] = 'quiz_result';
          $newfield['plugin_id'] = 'quiz_result_answer';
          $view
            ->setHandler($view->current_display, 'field', 'answer_' . $quizQuestion
            ->id(), $newfield);
        }
      }
      $fields = $view
        ->getHandlers('field');

      // Remove placeholder field.
      $view
        ->setHandlerOption($view->current_display, 'field', $field_name, 'exclude', TRUE);
    }
  }
}