lundi 30 mars 2015

New model instance with hasMany relationship from form data

I have two models:



// models/licenses.js
export default DS.Model.extend({
name: DS.attr('string'),
active: DS.attr('boolean'),
territoryType: DS.attr('string'),
territories: DS.hasMany('masterTerritory', { async: true }),
cities: DS.hasMany('city', { async: true }),
});


and



// models/license-type.js
export default DS.Model.extend({
primaryCity: DS.attr('string'),
region: DS.attr('string'),
licenseType: DS.belongsTo('licenseType', { async: true }),
});


I'm trying to create a new instance of the 'license' model from form data, including a select box containing licenseType data:



{{!-- templates/index.hbs --}}
...
{{view 'select'
contentBinding='controller.ddLicenseTypes'
optionLabelPath='content.name'
optionValuePath='content.id'
class='form-control'
value=newLicenseType
action='createLicense'
prompt='Select a License Type'
}}
...

// controllers/index.js
...
ddLicenseTypes: function() {
var store = this.get('store');
return store.findAll('licenseType');
}.property('store'),
...
actions: {
createLicense: function() {
var store = this.get('store');
var primaryCity = this.get('newPrimaryCity');
var region = this.get('newRegion');
var licenseTypeId = this.get('newLicenseType');
if(!primaryCity.trim()) { return; }
if(!region.trim()) { return; }
if(!licenseTypeId) { return; }

var license = this.store.createRecord('license', {
primaryCity: primaryCity,
region: region,
licenseType: store.find('licenseType', licenseTypeId), // What do I do here?
});

this.set('newPrimaryCity', '');
this.set('newRegion', '');
this.set('newLicenseType', '');

license.save();
},
}


My problem (as noted by 'What do I do here?') is in converting the licenseTypeId I retrieve from the select input back into a licenseType model object. The code above leaves licenseType empty, so when I submit it to my server it inserts the record with a NULL licenseType.


I've tried using and several other permutations of that same theme, but I have not hit upon the correct answer.


Thank you for your help.





Aucun commentaire:

Enregistrer un commentaire