III.1
Load and save definitions
You need this: When anyone other than a developer should change forms.
Survey Creator lets non-developers create and change forms in your application. For your backend, a definition is one more JSON document to load and save. Creator edits the definition your forms already load. Save it back through one endpoint; the next page load renders the new version. Saving definitions is an admin action: authorize it.
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/creator-load-save.js · sjs:III.1.client
View on GitHub
import { SurveyCreator } from "survey-creator-js";
const creator = new SurveyCreator({ showTranslationTab: true });
creator.JSON = (await fetch(`/api/forms/${formId}`).then(r => r.json())).definition; // the I.2 endpoint's .definition
creator.autoSaveEnabled = true; // save after each change; without it, Creator shows a Save button
creator.saveSurveyFunc = async (saveNo, callback) => {
const res = await fetch(`/api/forms/${formId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(creator.JSON)
});
callback(saveNo, res.ok); // tells Creator whether the save succeeded
if (!res.ok) creator.notify((await res.json()).error, "error"); // say why, e.g. 403: no editor rights
};
routes/examples/creator-load-save.php · sjs:III.1.server
View on GitHub
// PUT /api/forms/{id} — store the definition as-is: it's one JSON document
Route::put('/api/forms/{id}', function (Request $request, string $id) {
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
$definition = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
DB::table('forms')->updateOrInsert(['key' => $id], [
'json' => json_encode($definition, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR),
]);
return response()->noContent(); // the next page load renders the new version
});
Definition: shared/definitions/creator-load-save.json