SurveyJS ASP.NET Core Backend Integration /

Variable Presets

Commercial

Variable Presets

Test conditional logic with saved sets of sample variables in the Preview tab. Switch between scenarios, such as basic and premium subscription plans, to check which questions appear without changing the form schema.

Documentation

Try this

  1. In Preview, switch from Basic to Premium using the variable preset selector at the bottom. The customerTier variable controls whether the Call me back within one hour from field appears.
  2. Click Manage presets and edit a preset's customer plan or add a scenario. Preset changes are saved automatically, through the same auth.AuthorizeAsync(user, "edit-forms") check as Load and Save Form JSON Schemas.
  3. Reload the page to check that the edited presets were saved. Open Requests to inspect the requests that load and save presets.

SurveyJS commercial products require a developer license for production use. See SurveyJS Licensing for details.

Running master@a5dffdd

    No requests

      What the server stored

      JSON definition · shared/definitions/variable-presets.json View on GitHub
      {
        "title": "Support request",
        "elements": [
          {
            "type": "dropdown",
            "name": "product",
            "title": "Product",
            "choices": [
              "Form Library",
              "Survey Creator",
              "Dashboard",
              "PDF Generator"
            ]
          },
          {
            "type": "comment",
            "name": "issue",
            "title": "Describe the issue",
            "isRequired": true
          },
          {
            "type": "boolean",
            "name": "callback",
            "title": "Call me back within one hour",
            "description": "Available to customers on the premium plan",
            "visibleIf": "{customerTier} = 'premium'"
          }
        ]
      }
      Client · shared/client/variable-presets.js · sjs:variable-presets.client View on GitHub
      const creator = new SurveyCreator({
        variablePresets: {
          definition: {
            elements: [{
              type: "dropdown", name: "customerTier", title: "Customer plan",
              choices: [{ value: "basic", text: "Basic" }, { value: "premium", text: "Premium" }],
              isRequired: true
            }]
          },
          presets: []
        }
      });
      creator.onVariablePresetsChanged.add((_, options) => {
        // Switching scenarios changes only Preview; editing persists the preset list
        if (loaded && options.reason === "edit") { saver.changed(); saver.save(); }
      });
      Client · shared/client/variable-presets.js · sjs:variable-presets.save View on GitHub
      // Save the list, rather than wrapping it in another variablePresets configuration
      const saver = createSchemaSaver(() => creator.variablePresets.presets ?? [], async json => {
        const response = await fetch(`/api/variable-presets/${formId}`, {
          method: "PUT", headers: { "Content-Type": "application/json" }, body: json
        });
        if (!response.ok) throw await responseError(response, "Couldn't save the presets. Please try again.");
      }, ({ state, error }) => {
        if (!loaded) return;
        showError(state === "error" ? `${error} Your preset edits remain in this editor.` : "");
        retrySave.hidden = state !== "error";
        retrySave.disabled = state === "saving";
        if (state === "error") creator.notify(error, "error");
      });
      Server · Endpoints/VariablePresets.cs · sjs:variable-presets.server View on GitHub
      // GET /api/variable-presets/{formId} — return the stored preset list, or [] when none are saved
      app.MapGet("/api/variable-presets/{formId}", async (string formId, SurveyDb db) =>
      {
          var json = await db.VariablePresets.Where(p => p.Key == formId).Select(p => p.Json).SingleOrDefaultAsync();
          return Results.Text(json ?? "[]", "application/json");
      });
      
      // PUT /api/variable-presets/{formId} — store the variable presets as-is: it's one JSON document
      app.MapPut("/api/variable-presets/{formId}", async (string formId, HttpRequest request, ClaimsPrincipal user, IAuthorizationService auth, SurveyDb db) =>
      {
          var allowed = await auth.AuthorizeAsync(user, "edit-forms");   // editing is an admin action: 403 otherwise
          if (!allowed.Succeeded)
              return Results.Json(new { error = allowed.Failure?.FailureReasons.FirstOrDefault()?.Message }, statusCode: 403);
          // The raw body, not a bound class: binding would drop the keys the class doesn't know and re-format numbers
          var presets = await StoredJson.ReadBodyAsync(request);
          await StoredJson.UpsertAsync(db, StoredTable.VariablePresets, formId, presets);   // stored as it arrived: 1.0 stays 1.0
      
          return Results.NoContent();
      });