III.4
Variable presets
You need this: When form logic depends on variables your application supplies at runtime.
Variable presets (Creator v3.1.1) are named sets of sample variable values. Form authors switch between them in the Preview tab to test logic like "premium customers only", and use the variables in visual condition editors. Edits stay in memory until you save them: load and store the presets like any other JSON document.
This step on the Server Integration page
Source on GitHub
Commercial client licence: without SURVEYJS_LICENSE_KEY the component shows a licence banner
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/variable-presets.js · sjs:III.4.client
View on GitHub
import { SurveyCreator } from "survey-creator-js";
const creator = new SurveyCreator({
variablePresets: {
definition: { // describes the variables and how authors edit them
elements: [{
type: "dropdown", name: "customerTier", title: "Customer plan",
choices: ["basic", "premium"]
}]
},
presets: await fetch(`/api/variable-presets/${formId}`).then(r => (r.ok ? r.json() : []))
}
});
// Save the presets when an author edits them
creator.onVariablePresetsChanged.add((_, options) => {
if (options.reason === "edit") {
fetch(`/api/variable-presets/${formId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(options.variablePresets)
});
}
});
routes/examples/variable-presets.php · sjs:III.4.server
View on GitHub
// GET /api/variable-presets/{formId} — return the stored variable presets (404 if none yet)
Route::get('/api/variable-presets/{formId}', function (string $formId) {
$json = DB::table('variable_presets')->where('key', $formId)->value('json') ?? abort(404, 'No presets saved yet');
return response($json)->header('Content-Type', 'application/json');
});
// PUT /api/variable-presets/{formId} — store the variable presets as-is: it's one JSON document
Route::put('/api/variable-presets/{formId}', function (Request $request, string $formId) {
Gate::authorize('edit-forms'); // editing is an admin action: 403 otherwise
// The raw body, not $request->input(): PHP arrays would turn {} into [] in the stored JSON
$presets = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
DB::table('variable_presets')->updateOrInsert(['key' => $formId], [
'json' => json_encode($presets, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR),
]);
return response()->noContent();
});
Definition: shared/definitions/variable-presets.json