diff --git a/README.md b/README.md index f2d420c..1d38dc4 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,12 @@ model.save(); This will send the ``attachment`` and all other attributes as a FormData object. +## Customization + +You can override `getFormFields()` to select the fields you want to transform into FormData. The method is passed the model snapshot as unique parameter. If you want to customize the name for the key, overrides `getFormKey()` which is passed with the `key` and `value` for that key of the hash returned by `getFormFields()`. To customize the value, use `getFormValue()`. + +Do not abuse these customization. If you're performing huge changes in your model's representation, then you should be providing a custom serializer or maybe a different transformation for an specific field. + ### Thanks -This addon was inspired by Matt Beedle's blog post http://blog.mattbeedle.name/posts/file-uploads-in-ember-data/ \ No newline at end of file +This addon was inspired by Matt Beedle's blog post http://blog.mattbeedle.name/posts/file-uploads-in-ember-data/ diff --git a/addon/mixins/form-data-adapter.js b/addon/mixins/form-data-adapter.js index e14028a..8c4f3e9 100644 --- a/addon/mixins/form-data-adapter.js +++ b/addon/mixins/form-data-adapter.js @@ -13,13 +13,16 @@ export default Ember.Mixin.create({ if (typeof FormData !== 'undefined' && data && this.formDataTypes.contains(type)) { var formData = new FormData(); - var root = Ember.keys(data)[0]; - - Ember.keys(data[root]).forEach(function(key) { - if (typeof data[root][key] !== 'undefined') { - formData.append(root + "[" + key + "]", data[root][key]); + var fields = this.getFormFields(data); + + Ember.keys(fields).forEach(function(key) { + if (typeof fields[key] !== 'undefined') { + formData.append( + this.getFormKey(key, fields[key]), + this.getFormValue(key, fields[key]) + ); } - }); + }.bind(this)); hash.processData = false; hash.contentType = false; @@ -28,4 +31,17 @@ export default Ember.Mixin.create({ return hash; }, + + getFormFields: function (data) { + this._root = this._root || Ember.keys(data)[0]; + return data[this._root]; + }, + + getFormKey: function (key, value) { + return this._root + "[" + key + "]"; + }, + + getFormValue: function (key, value) { + return value; + } });