2

When taking a quiz with multiple questions, how do I get the current question's NID? The URL only contains the quiz' NID (node/1234), even when I started the quiz there only this NID is available (node/1234/take/1). When I node_load(arg(1)) there also is no clue of how and what questions are mapped to a quiz.

quiz-7.x-5.0-alpha10

  • You as an user? Or where would you need that? What file / hook / purpose? – Mołot Sep 16 '15 at 15:13
  • @Mołot – added background info. – leymannx Sep 16 '15 at 15:21
  • Wait, you put your logic in the templating layer?! Please don't. if you will, you will have future problems. Now it looks like you plan to hardcode "also correct" answers in template. It's bad idea, because you will have to edit your template each and every time answers will change. Correct way to do is to hook into quiz module and make it return all data needed. And if there are no hooks for that, patch it as needed or use something else. – Mołot Sep 16 '15 at 15:26
  • @Mołot – No, no, no! I don't want to put my logic into a template. Never! That only is the point where I finally need it as a simple CSS class string. – leymannx Sep 16 '15 at 15:27
  • 1
    @leymannx Perhaps this will help: quiz.module line 1810 - 1825, and line 3726 – J. Reynolds Sep 16 '15 at 20:02
1

Thanks a lot @J.Reynolds for pointing me in the right direction!

/**
 * Helper function to get current question's NID.
 * @return string node ID
 */
function _current_question_nid() {

  // Presume a URL node/1234/take/2 meaning we are at the second question
  // of a quiz, where arg(1) is the quiz NID

  // Now let's look inside SESSION. There's our current quiz NID.
  if (array_key_exists(arg(1), $_SESSION['quiz'])) {

    // Inside there is the current result ID.
    $result_id = $_SESSION['quiz'][arg(1)]['result_id'];

  } else {

    // A little bit different to get the current result ID at last question.
    $result_id = $_SESSION['quiz']['temp']['result_id'];

  }

  // Now we can load the quiz results from that result ID.
  $result = quiz_result_load($result_id);
  // There all question NIDs are inside, nicely ordered, yay!

  // Finally let's take the question number and get its NID.
  $current = $result->layout[arg(3)];
  return $question_nid = $current['nid'];
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.