lundi 22 décembre 2014

EmberJS - Forms with dynamic fields that are defined by the model

I want to build something that doesn't quite conform to any documentation or examples I've seen so far. Maybe what I'm trying is some kind of already known Bad Idea. Let me know if so.


I’m trying to figure out how to structure my controller and views around a server-side API that’s a little unusual. I have a form where I’m collecting some data, but the fields in the form need to be dynamic, based on data that comes from the server. Here’s an example of what the API returns (made-up example from a made-up domain for simplicity). I'm not using ember-data.


GET /event_color_choices?event_id=42&user_id=1



{
user_id: 1,
event_id: 42,
color_choices: [
// These will become form fields in the dynamic form.
// They won't be the same every time:
{
color: 'blue',
popularity: 100,
some_other_metadata: 'foo'
},
{
color: 'green',
popularity: 200,
foo: 'bar'
},
{
color: 'orange'
popularity: 150,
baz: 'qux'
}
]
}


So in my route, this data structure becomes my model:



App.EventChoicesRoute = Ember.Route({
model: function(params) {
return Ember.$.getJSON('event_color_choices' {
event_id: params.eventId,
user_id: params.userId
});
}
})


In my view, I'd like to do something like this (I think?):



{{#each colorChoice in color_choices}}
<label>How much do you like the color {{colorChoice.color}}?</label>
{{input type='text' value=???}} // <--- This is the part I'm having trouble with
{{/each}}


Should look something like:




How much do you like the color blue?

[[text input field here]]


How much do you like the color green? [[text input field here]]


How much do you like the color orange? [[text input field here]]




And when a user fills in the form, I'd like the model to be updated to become something like this, which I will send back up to the server on form submit:


POST /event_color_choices



{
user_id: 1,
event_id: 42,
color_choices: [
{
color: blue,
// ...
value: "I like blue a lot. It's my favoriate color."
},
{
color: 'green',
// ...
value: 'Green is just okay'
},
{
color: 'orange',
// ...
value: 'Orange is an okay starter color, for people who are just getting into colors'
}
]
}


Can I make ember do this? Should I be taking some other approach?





Aucun commentaire:

Enregistrer un commentaire