I've been racking my brain over this issue for a few days and cant come up with a decent solution.
I have the following model
{
"id": "123",
"key1": "foo",
"key2": "bar",
"metadata": {
"height": 1,
"width": 1
},
"userPrefs": [
{
"name":"firstName",
"displayName":"First name",
"required":true,
"dataType":"text",
"defaultValue":"enter first name",
"value": ""
},
......
]
}
My view uses this model, and specifically the userPrefs, to create an edit form. So for example the userPrefs would generate an input like so
<input type="text" id="firstName" name="firstName" value="" placeholder="enter first name" required />
A user may then enter a value for first name - e.g. "John" and click save. I need to map this form data back to the model before issuing a PUT request.
So I hijack the submit event and do
this.$('form').serializeArray()
this returns me an array of key/value pairs e.g.
[{"firstName": "John"}]
Now the issue I'm having is how best to map these value's back into the correct userPref in the model.
I toyed with the idea of 'assuming' 5 userPrefs would result in 5 inputs. I could then just use an iterator with an index to update the correct userPref. But as we know, an unchecked checkbox wont be submitted, so a simple iterator wont work.
Then I tried taking each serialised value and looping through the userPrefs for a match. But this would still fall over with the checkbox issue mentioned above.
Can anyone see an elegant solution to this?
- Is there a better json structure I should be using to get round this issue? perhaps a separate model containing only userPrefs
- How will I know if a user has unchecked a checkbox and be able to update my model