Quiz System Architecture
Current Storage and Runtime
Quiz settings specialize the project form, and question-specific quiz settings are stored with form fields in the current model. App integrations use declared form dependencies and page-context runtime helpers. Verify actual schema version, models and deployed quiz operations before copying an older endpoint/field example.
This guide describes the quiz architecture for platform contributors. The storage descriptions below summarize model responsibilities rather than providing executable migrations. Consult current migrations and model casts before changing storage. For attendee-app setup and tested lifecycle boundaries, see Quiz App Integration. For apps that run a live quiz, see Building a Live Quiz Control Panel.
The live quiz control, management API, channel and collection-sourced option sections below were reviewed against platform source at 208d36e1b5 on 2026-11-05.
Overview
The quiz system enables interactive assessments within the GxP platform, supporting:
- Multiple Question Types - Multiple choice, true/false, text, matching, ordering
- Scoring System - Configurable point values with partial credit
- Attempt Management - Limit attempts, track history, allow retakes
- Time Limits - Quiz-level and per-question timers
- Randomization - Shuffle questions and answer options
- Live Quiz Mode - Server-driven question activation for synchronized quizzes, controlled from the dashboard or from an app bound to the quiz
- Gamification Integration - Game-point rules and transaction integration
- Leaderboards - Configured score rankings; delivery timing depends on the deployed app/events
Data Model
Core Tables
project_forms (Quiz Configuration)
Quizzes use the existing project_forms table with form_type = 'quiz'. Configuration is stored in JSON columns:
| Field group | Responsibility |
|---|---|
id, project_id, name, slug, form_type | Project-scoped form identity; quiz forms use quiz |
custom_settings | Quiz configuration and policy choices |
dependency_list | Bound resources, including optional game and subject container |
trigger_state | Current live/page state |
root_config, cards_config, elements_config | v2 schema representation; inspect schema_version before translating |
Quiz Settings Structure (custom_settings)
This is an illustrative configuration, not the complete settings catalog or a declaration of defaults. Choose disclosure, timing and attempt settings for the intended assessment.
{
"create_game_session": true,
"randomize_questions": false,
"randomize_answers": false,
"question_limit": null,
"timed_quiz": true,
"quiz_time_limit": 1800,
"per_question_timer": false,
"default_question_time": 60,
"section_progression_locked": false,
"default_points_correct": 10,
"default_points_incorrect": 0,
"allow_partial_credit": true,
"max_attempts": 3,
"attempt_scoring": "highest",
"show_correct_answers": true,
"show_answers_when": "after_submit",
"show_score_during_quiz": true,
"show_leaderboard": true,
"leaderboard_type": "cumulative",
"single_bank_mode": false,
"active_bank_id": null,
"live_mode_enabled": false,
"live_multi_question_allowed": false,
"default_question_duration": 30,
"late_join_policy": "current_question"
}
form_fields (Quiz Questions)
Questions are stored as FormField records with is_quiz_question = true:
FormField relates to project_form_id and optional form_section_id, and stores question identity/order (slug, order), display/type (label, type), options, is_quiz_question and active state. Grading settings live under custom_settings.quiz; localized quiz feedback lives under language_overrides.quiz. Schema translation and the installed attendee app must agree on field type, style and question handler ID.
Question Settings (FormField.custom_settings.quiz.*)
{
"quiz": {
"question_type": "multiple_choice",
"correct_answers": ["option-2"],
"case_sensitive": false,
"points_correct": 10,
"points_incorrect": 0,
"answer_multipliers": {
"option-1": 0,
"option-2": 1.0,
"option-3": 0.5
},
"time_limit": 60
}
}
A multiple_choice question can also carry:
{
"quiz": {
"question_type": "multiple_choice",
"options_source": {
"collection_id": 58,
"label_field": "title",
"secondary_field": "artist"
},
"max_selections": 3,
"correct_answers": ["1201"]
}
}
options_source makes the question take its options from a collection instead of the options column; correct_answers then hold entry IDs as strings. max_selections limits how many options an attendee may pick. FormField::options_source returns null unless both collection_id and label_field are set; FormField::max_selections returns null unless the value is a positive number. See Collection-sourced options.
Question Feedback (FormField.language_overrides.quiz.*)
{
"quiz": {
"feedback_correct": "Correct! Great job.",
"feedback_incorrect": "Incorrect. The correct answer is Paris.",
"answer_explanations": {
"option-1": "London is the capital of the UK.",
"option-2": "Paris is the expected answer for this sample question."
}
}
}
quiz_attempts
| Field group | Responsibility |
|---|---|
| Form, attendee, bank, game/live-session references | Associate the attempt with its context |
subject_type, subject_id | Optional subject morph identity |
attempt_number, status | Numbering and in_progress / completed / timed_out / abandoned lifecycle |
| Question/answer counts, score, maximum, percentage | Stored totals, refreshed through scoring services |
| Start/completion times and elapsed seconds | Attempt timing |
question_order, metadata | Prepared slug order and context snapshot |
Attempt numbering uses separate partial unique indexes for unlinked attempts and subject-linked attempts. Linked identity includes form, attendee, subject type/ID and attempt number; do not assume one attendee-wide sequence across all subjects.
quiz_attempt_answers
Answers belong to quiz_attempt_id and identify a question by element_id. They store answer value, correctness, partial credit, awarded points, multiplier, timing and optional point-transaction/live-session links. AI submissions additionally use image metadata, scoring status and submission history metadata.
The migrated answer identity is UNIQUE(quiz_attempt_id, element_id, submission_number).
The answer identity includes submission_number; multiple rows for one attempt/question are supported. A failed asynchronous submission remains in history even when excluded from the retry-limit count. Do not collapse rows by element_id alone or infer the remaining allowance from the largest submission number. See the integration guide for pending scoring and retry reconciliation.
quiz_live_sessions
For live/synchronized quiz delivery:
QuizLiveSession stores the form reference, unique session_uuid, status, optional game session, current question/bank and ordered question sequence/index. It also stores review question/options, timing, metadata and creating/ending admins; those admin columns are null when an app acted through the management API. The creating hook supplies a UUID and start time when absent.
Statuses are no_session, waiting, question_active, review, leaderboard and ended. The active-status helper includes waiting, question-active, review and leaderboard. Review include-analytics/include-explanation columns default to true in the creation migration; an operation's options can change the actual disclosure behavior. Current question/bank IDs are nullable columns in that migration, not declared foreign-key constraints there. Consult the current schema rather than deriving constraints from model relationships.
Model Architecture
QuizSettings Model
QuizSettings extends ProjectForm over the same form storage. Its known setting keys are exposed through accessors backed by custom_settings; game identity comes from the dependency list. createRules()/updateRules() define supported settings validation. This is a model view of the form, not an independent quiz-settings table.
Key model responsibilities include:
canAttempt,getRemainingAttempts,getNextAttemptNumberandgetAttendeeScore, with optional subject context.getQuestionsandgetQuestionfor configured question lookup.isFreePlay, live-mode/state/window helpers and bank selection.startLiveQuestions,closeQuestions,closeLiveStateandresetLiveStatefor live state transitions. Each takes a nullable actor (null when an app acts) and an optional extra state merged in the same write.closeLiveStateends live mode but moves live windows intoclosed_question_windows;resetLiveStatealso wipes the window history. Both leave keys the quiz does not own in place.bankQuestionIdsfor a bank's question IDs in display order.
Related constants: DEFAULT_LIVE_IGNORE_KEYS (the keys attendees don't receive unless the quiz sets its own ignore_keys) and LIVE_SETTINGS_KEYS (the settings an app may change with update_live_quiz_settings alone: default_question_duration, live_multi_question_allowed, late_join_policy, timeout_behavior). SYSTEM_TRIGGER_STATE_KEYS and SYSTEM_TRIGGER_STATE_PREFIXES (session_, review_, leaderboard_) name the trigger_state keys live quiz owns; the Trigger State API refuses to write them on quiz forms and leaves them out of reads of another target, so apps change them only through the live quiz endpoints.
Use actual signatures from the current model when extending platform code; these helpers do not replace route authorization or subject eligibility checks.
FormField Quiz Methods
Quiz questions are FormField records with built-in grading methods:
// app/Models/FormField.php
// Accessors (via custom_settings.quiz.*)
$field->quiz_question_type; // Registered ID: single_choice, multiple_choice, etc.
$field->correct_answers; // Array of correct option IDs
$field->points_correct; // Points for correct answer
$field->points_incorrect; // Points (usually 0 or negative) for wrong answer
$field->time_limit; // Per-question time limit
$field->feedback_correct; // Feedback text for correct answer
$field->feedback_incorrect; // Feedback text for wrong answer
$field->answer_explanations;// Per-option explanations
// Grading methods
$field->isAnswerCorrect(mixed $answer): bool;
$field->calculatePartialCredit(mixed $answer): float; // 0.0 to 1.0
$field->calculatePoints(mixed $answer, bool $allowPartialCredit = false): int;
$field->getMultiplier(mixed $answer): float;
QuizAttempt Model
QuizAttempt stores attempt status, question order, subject identity, timing, totals and answer relationships. Its status constants are in_progress, completed, timed_out and abandoned. It exposes isInProgress(), isFinished(), getElapsedSeconds() and hasTimedOut(); answer recording, completion and scoring orchestration belong to services/handlers, not the removed model methods previously listed here.
Two helper details matter when writing recovery logic. isFinished() returns true for completed/timed-out attempts, but not abandoned ones; use the explicit status when deciding whether an attempt is no longer active. hasTimedOut() compares elapsed time with >=, whereas the reviewed controller open-attempt reconciliation and answer service expire on >. At the exact limit those helpers can disagree. Follow the server operation response and stored status rather than using one model helper as proof a lifecycle transition already ran.
Service Layer
QuizService
Location: app/Services/Quiz/QuizService.php
Primary orchestrator for quiz operations:
class QuizService
{
// Start a new attempt
public function startAttempt(
ProjectForm $form,
Attendee $attendee,
?int $bankId = null,
?Model $subject = null
): QuizAttempt;
// Submit answer for a question
public function submitAnswer(
QuizAttempt $attempt,
string $elementId,
mixed $answerValue,
?int $timeSpent = null
): array;
// Complete the quiz
public function completeAttempt(QuizAttempt $attempt): array;
// Get quiz state for attendee
public function getQuizState(
ProjectForm $form,
Attendee $attendee,
?QuizAttempt $activeAttempt = null,
?Model $subject = null
): array;
// Generate question order (with randomization)
public function prepareQuestionOrder(QuizSettings $settings, ?int $bankId = null): array;
// Get answer review for completed attempt
public function getAnswerReview(QuizAttempt $attempt): array;
// Get leaderboard position
public function getLeaderboardPosition(QuizAttempt $attempt): ?int;
}
Live quiz control services
The dashboard Live Control tab and the portal management API share these services, so both paths validate, write and broadcast the same way.
| Service | Location | Responsibility |
|---|---|---|
LiveQuizControlService | app/Services/Quiz/LiveQuizControlService.php | Every live control action: open, reopen, close and reset sessions; send and unsend questions; review; leaderboard; active bank; state and analytics reads. Writes run in a transaction on a freshly read, row-locked copy of the form, so concurrent trigger_state writers can't drop each other's changes. Actors are admin IDs, or null when an app acts |
QuizBankService | app/Services/Quiz/QuizBankService.php | Banks and questions: listings (answers only when asked for), bank status with the single-bank-mode check, and bank/question create, update, delete and reorder through the Quiz Builder's save path |
LiveQuizTally | app/Services/Quiz/LiveQuizTally.php | Counts for a question window, shared by the analytics endpoints and the analytics broadcast |
LiveQuizChannelAuthorizer | app/Services/Quiz/LiveQuizChannelAuthorizer.php | Who may join the dashboard admin channel and the app controller channels |
LiveQuizSessionService | app/Services/LiveQuizSessionService.php | QuizLiveSession rows: start, reopen, end, review, leaderboard, bank change and session analytics |
LiveQuizControlService turns the session service's missing-session or missing-question errors into 422 validation errors. It checks that question, bank and session IDs belong to the quiz before acting, and refuses opening a session or sending questions while live mode is off.
QuizBankService refuses edits to a bank that attendees may be answering: a bank whose status is active (a missing status counts as active), the live bank, the active bank in single-bank mode, or a bank holding a live question. The check runs under the form's row lock against fresh rows, so an activation or a send can't land between the check and the write. Quizzes whose structure lives in the layout graph are refused, because these writes don't maintain it.
unsend dispatches BroadcastLiveQuizQuestionAnalytics for each closed question after the transaction commits, so the final counts are broadcast even when the throttled per-answer broadcast missed the last answers.
API Layer
Quiz API Endpoints
The current v1 project route group uses /quiz/{form} beneath the configured API/project prefix. Resolve the deployed host, prefix, operation ID and dependency bindings from the REST catalog; the suffixes below are not standalone URLs.
| Suffix | Method | Description |
|---|---|---|
/state | GET | Reconcile state for the attendee and optional subject |
/subjects | GET | Retrieve eligible subjects when configured |
/start | POST | Start through attempt eligibility rules |
/restart | POST | Abandon the matching open attempt, then check allowance and start |
/questions | GET | Retrieve questions for the resolved active attempt |
/answer | POST | Submit type-specific answer data |
/answer/{elementId}/status | GET | Reconcile answer/scoring status |
/complete | POST | Complete the active attempt or use the supported completion fallback |
/timeout | POST | Time out the resolved active attempt |
/leaderboard | GET | Read the supported leaderboard response |
These routes do not accept an arbitrary attempt ID in the path. The controller resolves the current attendee and open attempt; subject context disambiguates concurrent subject attempts. The group removes ordinary Sanctum authentication but applies enforce.form.page.context. Attendee-app calls still need valid form-referencing page context and an attendee session for attempt operations. See the integration guide for 401/404/409/422 diagnosis and restart/timeout side effects.
Controller
Location: app/Http/Controllers/Api/Ver1/QuizController.php
class QuizController extends Controller
{
public function state(Request $request, ...): JsonResponse;
public function start(Request $request, ...): JsonResponse;
public function answer(QuizAnswerRequest $request, ...): JsonResponse;
public function complete(Request $request, ...): JsonResponse;
public function timeout(Request $request, ...): JsonResponse;
public function leaderboard(QuizLeaderboardRequest $request, ...): JsonResponse;
}
Live quiz management API
/quiz/{form}/manage/* (app/Http/Controllers/Api/Ver1/LiveQuizManagementController.php) lets an app page run a live quiz. {form} is the quiz's slug. The routes sit under the authenticated v1 project group and need an app page context: LiveQuizRequest resolves the quiz in the project and returns 404 unless the calling page isBoundTo it (it renders the quiz, or a ProjectForm dependency binds it by ID, slug, tag, * or a typed App\Models\ProjectForm:<id> value). The {form} parameter is not type-hinted, so implicit binding can't resolve the form without the project and the binding check.
Each request class names the ProjectFormPolicy method that guards it. The live quiz abilities are both admin permissions (rules.project_form) and app dependency abilities (api_routes.project_form):
| Policy group | Abilities |
|---|---|
LIVE_QUIZ_READS | view_live_quiz_state, view_live_quiz_analytics, view_live_quiz_history, view_quiz_banks, view_quiz_answers |
LIVE_QUIZ_CONTROLS | open_live_quiz_session, close_live_quiz_session, reset_live_quiz, send_live_quiz_questions, unsend_live_quiz_questions, review_live_quiz_questions, control_live_quiz_leaderboard, set_active_quiz_bank, update_quiz_bank_status, manage_quiz_banks, manage_quiz_questions, update_live_quiz_settings |
viewLiveQuizState also allows any control ability. For page keys, the policy additionally checks the request's permission plan through DataScopeService::allows, which is where an admin's dropped abilities apply. Sending a whole bank also needs set_active_quiz_bank. ignore_keys is prohibited unless an admin sends it.
api_routes.project_form.presets defines live_quiz_viewer, live_quiz_host, live_quiz_editor and live_quiz_admin. DependencyPermissionNormalizer, run by PluginPageVersionObserver::saving on every write path, expands a preset named in a dependency's permissions into its abilities (keeping a :scope suffix), so versions store abilities, not preset names. The migration that introduced the abilities granted all of them to every admin role holding manage_project_forms.
The endpoint list, request fields, responses and errors are in Building a Live Quiz Control Panel.
Frontend Architecture
Current source locations
The platform checkout contains the quiz builder and dashboard live controls below. It does not contain the previously listed resources/js/Portal/Components/Quiz/QuizRenderer.vue hierarchy. An installed attendee quiz app has its own implementation and release; do not treat a proposed component/state diagram as shipped platform source.
| Responsibility | Source location |
|---|---|
| v2 quiz builder | resources/js/Components/Mod/v2/CardElements/Builder/QuizBuilder/ |
| Builder definitions | resources/js/Components/Mod/v2/Definitions/CardElements/Builder/QuizBuilder.ts |
| Dashboard live controls | resources/js/Components/Quiz/LiveQuizControl.vue and sibling live components |
| Dashboard live state/subscriptions | resources/js/Composables/useLiveQuizAdmin.js |
| App controller channel helper | connectLiveQuizChannel in resources/js/Store/gxpPortalConfigStore.js |
| Dashboard analytics | resources/js/Components/QuizAnalytics.vue |
Attendee app state and API integration
An attendee app should reconcile server state before deciding whether to show eligibility, an active attempt or results. Pending scoring, expiry, abandoned attempts, free play and concurrent subjects require more than a fixed rules→active→completed diagram. See Quiz App Integration for these boundaries and the reviewed host-store import.
import { useGxpStore } from '@/stores/gxpPortalConfigStore'
const store = useGxpStore()
async function callQuizOperation(operationId, dependencyIdentifier, data = {}) {
return await store.callApi(operationId, dependencyIdentifier, data)
}
Select the operation ID and installed dependency identifier from the deployed catalog and app configuration. The identifier supplies authorized route bindings. Answer data includes the question's element_id, type-specific answer and applicable subject context; passing an invented attempt field does not select a historical attempt.
Live Quiz Mode
Architecture Overview
LiveQuizControlService runs every live action under the form's row lock and coordinates LiveQuizSessionService (persisted sessions) with QuizSettings.trigger_state:
- Opening a session ends an existing active session, optionally creates a game session, builds the question sequence and creates a waiting session. It synchronizes the session reference into trigger state.
- Sending questions needs live mode on, not an open session. When a session is open, the first sent question becomes its current question and
session_statusbecomesquestion_activein the same write as the windows.startLiveQuestionsprepares the question payload and timed windows. Single-question mode closes existing active windows intoclosed_question_windows; multi-question mode keeps them. - Question eligibility is evaluated from window status and server time.
getActiveQuestionWindows()includes an active window through itsend_at;hasQuestionWindowExpired()treats a closed window or a time afterend_atas expired. Answers afterend_atare refused, but nothing closes the stored window or broadcasts when the time passes: it staysactiveuntil an unsend, a later single-question send, or the end of live mode. - Unsending questions closes their windows, returns the session to waiting (or points it at a question still live) and broadcasts each closed question's final counts. Review and leaderboard operations update their own state; verify disclosure options and actual event delivery in the attendee app.
- Closing ends the active session (completing its game session) and calls
closeLiveState, which keeps the window history. Reset ends it and callsresetLiveState, which wipes the history.
Do not assume elapsed time alone persists a new session status or delivers a close event. Reconcile state/eligibility after reconnect and verify the deployed event paths described below. Subject-linked forms also have live-mode configuration restrictions; test the generic form-update path rather than treating subject and live settings as freely combinable.
Before activation, validateQuestionsForLiveBroadcast() checks the JSON-encoded combined formatted question list against 8,192 bytes and throws if it is larger; the control service reports that as a 422 under question_ids. The formatter selects ID/type/label/slug/required, quiz_question_type, option display/value/order/icon, points and an optional hint; it does not include the grading answer key. This helper-specific limit is not a universal limit on every quiz response, attachment or transport envelope.
Live State (trigger_state)
{
"live_mode": "active",
"live_bank_id": 5,
"live_question_ids": [11],
"mode": "single",
"question_windows": [{
"question_id": 11,
"bank_id": 5,
"start_at": "2025-01-15T10:00:00Z",
"end_at": "2025-01-15T10:00:30Z",
"duration_seconds": 30,
"status": "active",
"closed_at": null,
"initiated_by": 42
}],
"questions": [],
"session_id": 123,
"session_uuid": "uuid-here",
"session_status": "question_active",
"ignore_keys": ["updated_by", "initiated_by", "admin_analytics", "closed_question_windows"],
"updated_at": "2025-01-15T10:00:00Z"
}
A window carries max_selections when the send set a per-round pick limit. initiated_by and updated_by are null when an app made the change. When a quiz has no ignore_keys of its own, attendees still don't receive QuizSettings::DEFAULT_LIVE_IGNORE_KEYS; ProjectForm::attendeeTriggerState() removes the ignored keys from the state and from each live and closed window, skipping entries that aren't strings.
Broadcast paths and subscription checks
ProjectFormObserver::updated broadcasts when trigger_state changed. Channel strings below are the logical names passed to Laravel's private-channel API; the transport adds its private-channel prefix.
| Producer | Logical channel | Event alias / payload |
|---|---|---|
ProjectFormObserver → ProjectPageStateChanged | portal.forms.{formId}, and portal.pages.{formId} during the transition | ProjectPageStateChanged: the diff of the attendee-visible state (project_page_id, changes, updated_at); not sent when only ignored keys changed |
ProjectFormObserver → ProjectFormTriggerStateChanged (quiz forms) | dashboard.project.{projectSlug}.quiz.{formSlug}.admin and portal.forms.{formId}.live | trigger_state.changed: form_id, full trigger_state, event_type, updated_at |
QuizLiveAnalyticsUpdated | The dashboard admin channel and portal.forms.{formId}.live.analytics | analytics.updated: form_id, question_id, response counts and distribution |
QuizQuestionAnswered | quiz.{formSlug}.{attendeeId} | QuizQuestionAnswered, reference data |
Forms have their own portal.forms.{formId} state channel because form IDs and page IDs collide on portal.pages. The portal store subscribes form-backed pages to portal.forms.{formId}; the portal.pages.{formId} copy remains only for the transition. Analytics have their own channel because a broadcast can't be filtered per subscriber, and view_live_quiz_analytics is separate from view_live_quiz_state.
LiveQuizChannelAuthorizer authorizes the controller channels:
- The dashboard admin channel requires an admin who is super-admin or holds
view_live_quiz_stateor any control ability in the project. portal.forms.{formId}.liveand.live.analyticsrequire an app page (the page key, or the page key an attendee's browser sends as its bearer) in the form's project, passing its group gate, and allowedviewLiveQuizStateorviewLiveQuizAnalyticsby the policy with the page's compiled permission plan, so dropped abilities apply.
portal.forms.{formId} is authorized by TriggerStateChannelAuthorizer; see the Trigger State API. The portal channel file separately registers quiz.{formSlug} and quiz.{formSlug}.{attendeeId}; attendee callbacks check project membership and, for the individual channel, attendee identity.
The dashboard's useLiveQuizAdmin.js listens for .trigger_state.changed and .analytics.updated on the admin channel. Apps use the store's connectLiveQuizChannel(formId) for the two controller channels. A successful REST mutation or connected dashboard indicator does not prove an individual event arrived; reconcile through the state and analytics reads after a reconnect or a missed update.
Events & Listeners
Events
// Quiz events
QuizAttemptCompleted::class // Quiz finished
QuizAttemptTimedOut::class // Time limit reached
QuizQuestionAnswered::class // Answer recorded
QuizSectionChanged::class // Live section changed
QuizLiveAnalyticsUpdated::class // Analytics update (dashboard admins and controller apps)
ProjectFormTriggerStateChanged::class // Full live state for controllers
ProjectPageStateChanged::class // Attendee-visible state diff
Listeners and jobs
// Listeners
BroadcastLiveQuizAnalytics::class // Throttled analytics broadcasts
// Jobs
BroadcastLiveQuizQuestionAnalytics::class // One question's counts for its latest window
Gamification Integration
Game Configuration
Quizzes integrate with games via dependency_list.game_id:
$form->dependency_list = array_replace(
$form->dependency_list ?? [],
['game_id' => $game->id]
);
$form->custom_settings = array_replace(
$form->custom_settings ?? [],
['create_game_session' => true]
);
// Persist through the authorized form update workflow.
Point Award Flow
QuizScoringService owns point awards. awardGamePoints() chooses the award/penalty event by earned points: positive points use quiz_question_correct, otherwise quiz_question_incorrect. A positive partial-credit answer can therefore use the award rule even when its binary is_correct value is false.
The service resolves a matching point rule; without one it returns without creating a transaction. Transaction points depend on rule scope and multiplier configuration, so quiz score and game transaction points are not universally identical. The created transaction carries an answer-based idempotency key and quiz metadata, and the answer stores its point_transaction_id. Verify actual installed game/rule bindings and totals in the target project.
awardRetryableGamePoints() skips nonpositive answers, ignores later submissions in first mode and, in best mode, skips a new answer that does not improve on the previously linked answer. When replacing an award, it flags the old transaction and clears its old answer link before awarding the replacement. This is service behavior to test with the configured transaction backend; it does not establish exactly-once delivery across every handler or asynchronous failure.
Question Banks
Structure
Questions are organized into banks (form sections) with status:
// FormSection quiz bank settings
$section->custom_settings = [
'quiz_bank' => [
'status' => 'active', // 'active', 'draft', 'archived'
'description' => 'Product Knowledge Questions'
]
];
Bank Modes
Ordinary preparation uses the resolved bank or a nonempty active-bank set. If no active banks exist, the helper omits the bank filter and can return active fields under draft/archived banks. The public start handler does not expose an arbitrary bank-slug selector, and free play has a separate active-bank check. See bank selection and question order before relying on bank status as a delivery constraint.
Collection-sourced options
QuizOptionSourceResolver (app/Services/Quiz/QuizOptionSourceResolver.php) builds a multiple_choice question's options from the collection named in options_source:
- One option per entry in the collection and the form's project, whatever the entry's status. Soft-deleted entries are excluded by the model's scope.
valueis the entry ID as a string;labelis the label field's value, orEntry #<id>when it is empty;secondaryis added when a secondary field is set. Array values are joined with,.- Options are sorted by label with natural, case-insensitive ordering.
- The list is cached for up to an hour under the
collection_{id}_entriescache tag, which entry writes flush.
assertValidSource() refuses a collection outside the form's project or a field the collection does not define. It runs on every save path: the Quiz Builder (ProjectFormService::updateFormDefinition, which checks every quiz question before writing anything), the dashboard question update, and QuizBankService question create and update. The builder save also refuses a max_selections below 1. The dashboard route GET forms/{form}/quiz/source-options (under the project dashboard prefix, for admins who can view the form and the collection) previews a source's options before the question is saved; the dashboard question update also needs view access to the collection.
The resolved options replace the stored ones wherever options are formatted: AbstractQuestionType::formatChoiceOptions (quiz questions API and management listings), FormFieldResource, and QuizSettings::formatQuestionForLiveBroadcast. The live formatter keeps them compact (label, value, secondary), since they count toward the 8,192-byte live question limit, and adds quiz_question_type and the question's max_selections. FormSchemaTranslatorService exposes them to the builder as display-only sourceOptions, which are in its ignore list so a builder save can't turn them into static options.
Pick limits and answer checks
max_selections on a live send is stored on each new question window, not on the question. QuizService::guardChoiceAnswer() runs for multiple_choice answers before scoring:
- For a collection-sourced question, it normalizes the answer to unique string entry IDs and refuses any value that is not an option.
- It takes the limit from the active, unexpired window (
QuizSettings::getActiveWindowFor) while live mode is on, else from the question, and refuses more unique picks than that.
Refusals throw QuizAnswerRejectedException, whose message the answer endpoint returns as-is in a 422 (That answer is not one of the options., Pick one option., Pick at most <n> options.). Answers to a question's own options are not checked against the option list. With several picks, the immediate-feedback explanation is a map of the picked options' explanations.
Per-option tallies
LiveQuizTally::distribution() counts a multiple_choice answer once for each unique option picked; other list answers still count as one comma-joined combination, and scalar answers by value. total_responses counts answers, so per-option shares of respondents can sum past 100%. The window analytics, the analytics broadcast and LiveQuizSessionService::getSessionAnalytics() all use this distribution. The dashboard's Live Control analytics label collection options with the entry's label.
Development Guidelines
Adding a New Question Type
- Implement the
QuestionTypeHandlercontract, usually throughAbstractQuestionType, and register the handler in theQuestionTypeRegistrysingleton inAppServiceProvider. - Define the type ID, field type/style, settings defaults/validation, answer rules, API formatting and scoring behavior. Choose the actual submission strategy: synchronous, asynchronous or accumulative.
- Update builder definitions/editors in the existing v2 quiz builder and the separately installed attendee app's rendering/input support. There is no platform
QuizQuestion.vuedispatcher at the previously documented path. - Test invalid input, correctness/partial credit, API representation, retries and the selected strategy's persistence/recovery behavior. Field grading methods delegate to the registered handler; adding a UI option alone does not implement a new type.
Extending Quiz Settings
- Add key to
QuizSettings::$quizSettingsKeysarray - Add validation rule in
QuizSettings::createRules() - Use via magic
__get()accessor
Testing
Run PHP through Docker. From the platform checkout, ./bin/gxp test:unit, ./bin/gxp test:feature and ./bin/gxp test:js select the repository's hermetic test stacks; inspect their documented setup before running a full suite. Unit/integration tests use the current testing/ tier wiring, while older tests also remain under tests/. A file existing in the repository does not mean the default suite discovers it or that it passes.
Current examples include:
| Test file | Scope |
|---|---|
testing/Integration/Services/QuizSubjectLinkingTest.php | Subject configuration, eligibility and service limits |
testing/Feature/Api/Ver1/QuizSubjectApiTest.php | HTTP subject/start behavior |
testing/Integration/Console/FailStuckQuizScoringAnswersTest.php | Stale scoring recovery |
tests/Unit/Services/Quiz/QuestionTypes/QuestionTypeHandlerTest.php | Registered question handlers and grading |
tests/js/Components/QuizBuilder/QuizSubjectOverridePanel.test.js | Builder subject overrides |
testing/Feature/Api/Ver1/LiveQuizManagementTest.php | App management API: abilities, binding, foreign IDs, answer redaction, bank locks |
testing/Feature/Admin/Project/LiveQuizControllerTest.php | Dashboard Live Control endpoints |
testing/Integration/Permissions/LiveQuizChannelAuthorizerTest.php | Admin and app controller channel access |
testing/Integration/Observers/ProjectFormObserverLiveTest.php | Attendee and controller state broadcasts |
testing/Integration/Observers/PluginPageVersionPresetsTest.php | Preset expansion when a version saves |
testing/Integration/Services/QuizCollectionOptionsTest.php | Collection-sourced options and source validation |
testing/Feature/Api/Ver1/QuizChoiceAnswerTest.php | Option and pick-limit checks on answers, per-option tallies |
The live quiz rows were added with this update and were not run for it. The docs review ran selected source-matched cases in disposable offline fixtures. That evidence does not certify every row above, a full production database migration, deployed queue/broadcast delivery or attendee-app acceptance. Re-run relevant project suites when changing behavior, and record the command, source revision and actual result.
Performance Considerations
Query and cache behavior
Stored question order is a sequence of slugs; it does not itself guarantee a fixed query count. Profile the operation and eager-load the relationships it actually uses rather than assuming a slug list eliminates N+1 lookups. The analytics service groups answer rows by element_id and maps them onto quiz fields; retries and identifier representations matter when interpreting counts. Do not equate answer-row counts with unique learners without checking the selected metric.
The observer invalidates form/portal caches on changes, while some scoring calculations cache derived data. When adding caches, include the relevant project/form/subject/session scope and invalidation path. Measure the deployed query plan and freshness requirements before promising latency, throughput or real-time rankings.
WebSocket Throttling
BroadcastLiveQuizAnalyticstakes a one-secondCache::addmarker per form/question. The first answer in a window broadcasts right away throughBroadcastLiveQuizQuestionAnalytics; later answers in that window schedule one trailing broadcast a second later, so the last answers before a close are not dropped. Delivery also depends on queue and broadcast configuration.- Unsending questions dispatches their final counts after the transaction commits.
ignore_keysfiltering reduces the attendee payload size.- The attendee-visible
ProjectPageStateChangedis skipped when only ignored keys changed; the full-state controller broadcast is not.
Security Considerations
Answer visibility
Correct-answer visibility is configuration dependent. The answer response includes the correct answer when show_correct_answers is enabled with immediate disclosure; completion results include answer review for the supported after-submit/immediate settings. Validate the actual response for each question type and disclosure mode before publishing an assessment. Do not embed a private answer key in an attendee app's JavaScript bundle.
Authorization
Attendee-app requests cross separate page/form and attendee boundaries. The page must pass its audience gate and reference the form; attempt operations resolve the attendee's own current attempt. Supplying a form slug, reader credential or guessed attempt ID is not a replacement for this context. Test excluded audiences, other attendees, other projects and subject eligibility against the deployed routes. Admin actions and event subscriptions have their own policy/channel checks and need separate acceptance tests. Live quiz control from an app needs the binding and a separate ability per endpoint; test an unbound app (404), a missing or dropped ability (403) and IDs from another quiz (422).
Rate limiting and payload constraints
The reviewed quiz route group does not declare the per-operation rate limits previously listed here. Effective throttling can come from surrounding middleware or deployment infrastructure; verify that configuration and handle actual 429 responses rather than relying on invented quotas. The live activation helper checks its combined formatted question list against 8,192 bytes; other response/transport paths need their own verification. A local source review does not establish deployed channel access, delivery timing or infrastructure limits.
Related Documentation
- App Developer README - Building quiz apps for the platform
- Form Builder v2 (repository reference:
../form-builder/) - Question schema structure - Gamification System (repository reference:
../gamification/) - Game integration - Portal System (repository reference:
../portal/) - Embedding quizzes