Reputation: 1169
I have model like this:
defaults:{
id:'',
name: '',
type: new typeCollection()
},
parse: function(response){
var self = this;
var typeCol = typeCollection;
typeCol.fetch({ data: $.param({ id: response.id}),
success: function (collection, response) {
self.set('type', response);
}}
});
return response;
...
console.log(model.attribute)
//{"id":"7","name":"myName","type":[{"tid": "2","tName": "myTName"},{"tid": "3","tName": "mOTName"}]}
View:
Marionette.ItemView.extend({
template: _.template(myTpl),
initialize: function(options){
this.model = options.model;
this.listenTo(this.model, 'change', this.render);
},
events:{
"click #saveChanges":"saveIt"
},
saveIt: function(e) {
e.preventDefault();
var form = this.$('#basic_info');
var arr = form.serializeArray();
var data = _(arr).reduce(function(acc, field) {
acc[field.name] = field.value;
return acc;
}, {});
this.model.save(data);
console.log(data)//{"id":"7","name":"yourName","tName[0]": "myTName","tName[1]": "mOTName"}
Template: UPDATE: added index to tName
<form id="basic_info">
<input name="myName" value="<%= myName%>" type="text">
<% _.each(type, function(item, index) { %>
<input name="tName[index]" value="<%= item.tName %>" type="text">
<% }); %>
</form>
This works, it fulfils inputs fields. But I am not able to update (save()) nested "type" collection. How can I proper update nested collection and not lose "connection" to his parent model?
Thanks to your answer and comments I make it works, I had to change template and the way how I grab data from the form.
Here is solution:
Template:
<% _.each(type, function(item) { %>
<div data-nested="true" data-item-id="<%= item.tid %>" >
<input name="itemName" value="<%= item.tName %>" type="text">
</div>
<% }); %>
View:
//serialize only static part of the form
var rootInfo = _.object(_.map($('.serialize :input').serializeArray(), _.values))
var type= [];
form.find('div[data-nested=true]').each(function(){
var self = $(this);
var tid = self.data('item-id');
var tName= self.find('input[name=itemName]').val();
type.push({'tid' :tid,
'tName':tName })
})
//merge basic info with type
_.extend(rootInfo , {type:type})
this.model.save(rootInfo);
Upvotes: 0
Views: 274
Reputation: 7169
Form can have only one field with name tName / tid so try to change your template for example as
<form id="basic_info">
<input name="myName" value="<%= myName%>" type="text">
<% _.each(type, function(item) { %>
<input name="tName[]" value="<%= item.tName %>" type="text">
<% }); %>
</form>
then you've got ability to get all data and manipulate with it before save
you'll get an array of fields in formData, so you need to set needed fields as array to model field. If you need code example - please create test from at jsbin at give the link - community will add code
Upvotes: 2