Skip to content
This repository has been archived by the owner on Jun 5, 2024. It is now read-only.

Dynamic form generation

kuhlaid edited this page Apr 24, 2020 · 2 revisions

Question: Does it make sense to use dynamic form generation within this PWA, and if so what would that look like?

We should define a static form first. A static form is simply a form that is hard-coded into a page/component of the PWA. You cannot add a new form field for example without changing the PWA code. Dynamic form generation on the other had means having the PWA dynamically build a form that will be used to work with the data. The think is that when the PWA requests data from the data API, the data AS WELL AS the data definitions are sent to the PWA. The PWA then reads the data definitions and creates the form based on the data being sent from the API.

Does this make sense? Maybe. However this depends primarily on what needs to be accomplished within the PWA. At the very least if provides us some flexibility when working with data structure that may change depending on conditions and users.

I suggest this module because it provides a great starting point: svelte-formly

If using svelte-formly be sure to use valid JSON for your form field configuration like the following.

[
   {
      "type":"text",
      "name":"name",
      "label":"Produce name:",
      "value":"",
      "id":"name",
      "class":[
         "form-control"
      ],
      "placeholder":"Enter name of produce",
      "validation":[
         "required"
      ],
      "messages":{
         "required":"Produce name field is required!"
      },
      "description":{
         "class":[
            "custom-class-desc"
         ]
      }
   },
   {
      "type":"text",
      "name":"price",
      "label":"Price:",
      "value":"",
      "id":"price",
      "class":[
         "form-control"
      ],
      "placeholder":"Enter produce price",
      "validation":[
         "required"
      ],
      "messages":{
         "required":"Price is required!"
      },
      "description":{
         "class":[
            "custom-class-desc"
         ]
      }
   },
   {
      "type":"text",
      "name":"description",
      "label":"Produce description:",
      "value":"",
      "id":"name",
      "class":[
         "form-control"
      ],
      "placeholder":"Enter produce description",
      "validation":[
         "required"
      ],
      "messages":{
         "required":"Description field is required!"
      },
      "description":{
         "class":[
            "custom-class-desc"
         ]
      }
   }
]

...the reason for this is it allows you to store the JSON string in an indexedDb and then dynamically pull it into your Svelte app by simply retrieving the JSON string from the database and parsing it to JSON and assigning to the 'fields' variable in your component.