Category: UI Widgets
Updated

2023-08-03

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

How do I dynamically populate a list or form from query values?

Issue

As an app developer, I need to know how to dynamically populate a list or form with query values. This will help me display the results of a query or API in a user-friendly way and make data entry easier for users.

Resolution

The solution involves using the response of a query to populate a list or form dynamically. In the sample app provided, the code retrieves a list of items from a database query and populates an HTML select element with the results.

To achieve this, the code first sends a request to the backend API to fetch the query results. Upon receiving the response, the code formats the results into the expected format for the select element by looping through each item in the response and creating an option element for each item.

Here is an example code snippet that populates a select element with the results of a query:

// Send API request to fetch query resultsconst response = await fetch('/api/query');const data = await response.json();// Reference the select element in HTMLconst selectElement = document.querySelector('#my-select');// Loop through query results and add to select elementdata.forEach((item) => {  const optionElement = document.createElement('option');  optionElement.value = item.id;  optionElement.innerText = item.name;  selectElement.appendChild(optionElement);});

For generating a form dynamically from query/API fields, the JSON Form widget can be used. The widget can take a JSON schema definition as input, which describes the fields and their properties, and generate a form based on the schema. Here is an example code snippet:

// Send API request to fetch JSON schemaconst response = await fetch('/api/schema');const schema = await response.json();// Reference the DOM element to render the formconst formElement = document.querySelector('#my-form');// Use the JSON Form widget to generate the formJSONForm.render(formElement, schema, { /* options */ });

Overall, the solution involves fetching query results or JSON schema using an API request, and then using the results to dynamically populate a list or generate a form using JavaScript.