SurveyJS Java Backend Integration with Spring Boot /

Load Choices from Web

MIT

Load Choices from Web

Load choice lists from APIs and update them when related answers change. For example, changing a region reloads the office list with matching options from your backend.

Documentation

Try this

  1. Select an Office, then change the Region. The previous office selection is cleared, and the backend supplies offices in the new region.
  2. Choose Your country from a separate list served by the Spring Boot app. The backend caches the list and uses bundled choices if the external service is unavailable.
  3. Press Complete to save your answers, then open Data to inspect the stored office ID and country code.
  4. Open Requests to inspect the office and country lookups, including the example authorization header.
  5. Press Start over to reset the form.

Running main@d532820

    No requests

      What the server stored
      JSON definition · shared/definitions/choices-from-web.json View on GitHub
      {
        "title": "Choose an office",
        "elements": [
          {
            "type": "panel",
            "name": "find_office",
            "elements": [
              {
                "type": "radiogroup",
                "name": "region",
                "title": "Region",
                "colCount": 3,
                "defaultValue": "europe",
                "isRequired": true,
                "choices": [
                  {
                    "value": "europe",
                    "text": "Europe"
                  },
                  {
                    "value": "americas",
                    "text": "Americas"
                  },
                  {
                    "value": "asia-pacific",
                    "text": "Asia-Pacific"
                  }
                ]
              },
              {
                "type": "dropdown",
                "name": "office",
                "title": "Office",
                "isRequired": true,
                "choicesByUrl": {
                  "url": "/api/offices?region={region}",
                  "valueName": "id",
                  "titleName": "name"
                }
              }
            ]
          },
          {
            "type": "dropdown",
            "name": "country",
            "title": "Your country",
            "isRequired": true,
            "choicesByUrl": {
              "url": "/api/countries",
              "valueName": "code",
              "titleName": "name"
            }
          }
        ]
      }
      Client · shared/client/choices-from-web.js · sjs:choices-from-web.client View on GitHub
      // Use choicesByUrl in the form definition to load lists from API endpoints
      //   "choicesByUrl": { "url": "/api/offices?region={region}", "valueName": "id", "titleName": "name" }
      //   "choicesByUrl": { "url": "/api/countries", "valueName": "code", "titleName": "name" }
      // SurveyJS replaces {region} with the selected region and reloads the office list when the region changes
      
      // Optional: add your auth header to every choices request
      import { settings } from "survey-core";
      settings.web.onBeforeRequestChoices = (_, options) => {
        options.request?.setRequestHeader("Authorization", `Bearer ${token}`);
      };
      Server · src/main/java/io/surveyjs/examples/ChoicesFromWebController.java · sjs:choices-from-web.server View on GitHub
      // GET /api/offices?region= — {region} from the form arrives as a query parameter
      @GetMapping("/api/offices")
      public List<Office> offices(@RequestParam(defaultValue = "") String region) {
          return jdbc.sql("SELECT id, name FROM offices WHERE region = ? ORDER BY name").param(region).query(Office.class).list();
      }
      
      // GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
      @GetMapping("/api/countries")
      public ResponseEntity<List<Country>> countries() {
          List<Country> countries = cache.get("countries");
          if (countries == null) {
              try {
                  JsonNode all = restcountries.get().uri("https://restcountries.com/v3.1/all?fields=name,cca2").retrieve().body(JsonNode.class);
                  countries = all.valueStream().map(c -> new Country(c.get("cca2").asString(), c.get("name").get("common").asString()))
                          .sorted(Comparator.comparing(Country::name)).toList();
                  cache.put("countries", countries, Duration.ofHours(24));
              } catch (RuntimeException e) {   // down, or a different answer: the bundled list for 10 minutes, not a timeout each
                  log.warn("restcountries.com failed (" + e.getMessage() + "); serving shared/seed/countries.json");
                  countries = json.readValue(BUNDLED_COUNTRIES.toFile(), new TypeReference<List<Country>>() { });
                  cache.put("countries", countries, Duration.ofMinutes(10));
              }
          }
          return ResponseEntity.ok().cacheControl(CacheControl.maxAge(Duration.ofDays(1)).cachePublic()).body(countries);
      }