Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/
This addon was inspired by Matt Beedle's blog post http://blog.mattbeedle.name/posts/file-uploads-in-ember-data/
28 changes: 22 additions & 6 deletions addon/mixins/form-data-adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}
});