Dynamically generate and manage a form from a variable-length JSON array with mixed input types?

Hello Retool community,

I'm trying to solve a dynamic UI problem. I have a resource that returns a JSON array, where each object defines a field that needs to be rendered in a form. The challenge is that the length of this array is unknown, and the input type for each field is specified within the object itself.

Here's an example of the data structure I receive from getFormSchema.data:

[
  {
    "id": "user_name",
    "label": "Full Name",
    "type": "textinput",
    "defaultValue": "John Smith",
    "required": true
  },
  {
    "id": "user_age",
    "label": "Age",
    "type": "numberinput",
    "defaultValue": 30,
    "placeholder": "Enter your age"
  },
  {
    "id": "is_subscribed",
    "label": "Subscribe to newsletter?",
    "type": "switch",
    "defaultValue": true
  },
  {
    "id": "user_department",
    "label": "Department",
    "type": "select",
    "defaultValue": "eng",
    "options": [
      {"label": "Engineering", "value": "eng"},
      {"label": "Marketing", "value": "mkt"},
      {"label": "Sales", "value": "sls"}
    ]
  }
]

My goal is to:

  1. Render this array as a form, where each object becomes a form field (e.g., a TextInput for "textinput", a Switch for "switch").
  2. Store the user's input in a way that can be easily submitted.
  3. On submit, I need to send back a single key-value JSON object, like {"user_name": "Jane Doe", "user_age": 35, "is_subscribed": false, "user_department": "mkt"}.

I'm thinking of using a ListView component, but I'm struggling with how to dynamically render different component types within it and how to aggregate all the state from these dynamic components into a single object for submission. What's the best practice for achieving this?

1 Like

Hi @harry48,

So good news is we have a JSON Schema Form component to dynamically generate forms based on input fields specified in the provided data source. Check out our docs here for a quick tutorial.

Less good news is I was just testing the component out with your example and it seems to need some additional formatting to help the component understand what to build.

One option to first test is setting the data source to be the DB table you are using for uploading the inputs, if you have a table with columns for user_name, user_age, is_subscribed, and user_department as you have in your example, the forum will be able to read that from the table and should work properly with that.

If this does not work, another option would be to get the Array of JSON payload, do some JS script formatting to get it sanitized so that the component can play nicely with it and that should be a good backup option.

1 Like

Hi @harry48,

Just wanted to check in and see if the docs link i provided was helpful. Let me know if you were able to test out any of my suggestions!

1 Like