I.2
Load the definition, variables and previous answers
You need this: When the form depends on who is answering, or edits an existing record.
Three things can come from your server, each optional. The definition, rendered into the page as-is or with per-request changes, or fetched. Variables: application data the form reads in titles and conditions but never saves (the signed-in user, their plan, their locale). Previous answers: the stored response, so the form edits a record instead of starting blank.
Try this
Code that just ran
These regions are read from the files that served this page, the same lines the Server Integration page shows.
shared/client/load-definition-variables-data.js · sjs:I.2.client
View on GitHub
import { Model } from "survey-core";
async function createSurvey(recordId) {
if (window.FORM_DEFINITION) {
// Option A — your server rendered the definition into the page
return new Model(window.FORM_DEFINITION);
}
// Option B — one request returns the definition, variables and previous answers
const { definition, variables, data } =
await fetch(`/api/forms/claim-request?record=${recordId}`).then(r => r.json());
const survey = new Model(definition);
survey.setVariables(variables); // all at once; read as {user.name}, {plan}… and never saved with the response
survey.data = data; // previous answers: edit instead of starting blank
return survey;
}
routes/examples/load-definition-variables-data.php · sjs:I.2.server
View on GitHub
// Option A — render the definition into the page: no database, no extra request
Route::get('/claim', function () {
$definition = json_decode(file_get_contents(base_path('shared/definitions/load-definition-variables-data.json')));
$definition->title = 'Hi '.Str::before(Auth::user()->name ?? 'there', ' '); // change it per request if you like
return view('examples.load-definition-variables-data', ['definition' => $definition]); // Js::from() escapes it for an inline script
});
// Option B — definition, variables and previous answers in one response
Route::get('/api/forms/{id}', function (Request $request, string $id) {
$user = Auth::user();
$definition = DB::table('forms')->where('key', $id)->value('json') ?? abort(404, 'Unknown form');
$data = $request->filled('record') ? DB::table('responses')->where('id', $request->query('record'))->value('data') : null;
return response()->json([
'definition' => json_decode($definition), // a stored document, as stored
'variables' => ['user' => ['name' => $user?->name, 'plan' => $user?->plan]],
'data' => $data === null ? new stdClass : json_decode($data), // previous answers, or {}
], options: JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION);
});
Definition: shared/definitions/load-definition-variables-data.json