Skip to main content

Creating Drupal Quiz Nodes Programmatically

May 08 '15

Drupal Quiz Module 5The Drupal Quiz Module is a great option for implementing quizzes, tests and assessments of all stripes. Unfortunately the huge array of features keeps the developers pretty busy and the documentation can be a little sparse.

Here's a simple example of creating a question and attaching it to a quiz.

In the Drupal Quiz module, quizzes and questions are both node types (at least currently). Creating them is just like creating any other node programmatically, with a couple extra steps.

First, build a quiz node:

global $user;
$quiz = new stdClass();
$quiz->title = 'Loyalty Test';
$quiz->type = 'quiz';
$quiz->language = LANGUAGE_NONE;
$quiz->uid = $user->uid; 
$quiz->status = 1;
$quiz = node_submit($quiz);

Next, create a question node. We'll use question type "multichoice" but there are many others to choose from; each will differ slightly from what is shown below.

$question = new stdClass();
$question->title = 'User is a fan';
$question->uid = $user->uid; 
$question->type = 'multichoice';
$question->language = LANGUAGE_NONE;
$question->status = 1;
$question->body = array(LANGUAGE_NONE => array(array('value' => 'Do you totally love this website or what?')));
// These are some of the quiz options.
$question->choice_multi = 0;
$question->choice_random = 0;
$question->choice_boolean = 0;
// Possible answers go in the "alternatives" array.
$question->alternatives = array(
    'answer' => array(
      'value' => 'Yes',
    // All these values are necessary to avoid integrity constraint errors.
    'answer_format' => 'plain_text',
    'feedback_if_chosen_format' => 'plain_text',
    'feedback_if_not_chosen_format' => 'plain_text',
    'score_if_chosen' => 1,
    'answer' => array(
      'value' => 'No',
    'answer_format' => 'plain_text',
    'feedback_if_chosen_format' => 'plain_text',
    'feedback_if_not_chosen_format' => 'plain_text',
    'score_if_chosen' => 0,
$question = node_submit($question);

Now we have our quiz and question nodes; all that's left is to relate them.

module_load_include('inc', 'multichoice', 'multichoice.classes');
$question_wrapper = new MultichoiceQuestion($question);
$question_wrapper->saveRelationships($quiz->nid, $quiz->vid);
// Lastly we update the scoring data for the quiz node.

Read more about: