I’m kind of lost on how to work with states with Dynamic forms.
I surely cannot create states for each Field because I don’t know how many fields are there as these Forms are basically built from a JSON Response.
Here is basically what I have right now which is what I’m looking to change.
Initially I created a state for each field back when the forms were not built dynamically and now I’m stuck on how to proceed.
I thought about using Dictionary but I ain’t sure how good of a solution is that.
@State var textfieldText: String = ""
@State var SKU: String = ""
@State private var showScanner: Bool = false
var currentForm: FormModel
@State var RecordDate: Date = Date.now
@State var Formresponse: [String: Any] = [:]//This one is set to any because the value can vary from a string to [] to even a whole object
How I’m Rendering my form :
ForEach(currentForm.item, id:.idf) { it in
if (!it.questionItem.hidden)
{
switch it.questionItem.questionType {
case .dateQuestion :
DateField(title: it.title, currentDate: $RecordDate)
case .choiceQuestion:
Text("choice question")
case .scannerQuestion:
ScannerField(title: it.title, SKU: $SKU, showScanner: $showScanner)
case .textQuestion:
TextQuestionField(title: it.title, email: currentForm.owner, text: $textfieldText)
}
}
}
I’ll eventually have to submit this data in a form of dictionary which is why I thought about using a Dict ["fieldID":"FieldInput","fieldId2":"FieldInput2"..]
2
Answers
I think you only need one
State
and that is for theformResponse
. You can pass that as aBinding
to each input field view and within that view you can create a customBinding
to get and set the answer to theformResponse
. Something like this:define enum for the questions type:
define the item model for the questions type:
define the form view model:
and the view :
and here’s the dummy values for the form:
and the result: