PDA

View Full Version : How can I configure the model proxy to send the simple model as key-value pair?



panpawel
9 Nov 2011, 9:21 AM
I have a simple model and I want to send my single model as a key-value pairs (query string), not as a JSON format? Is there a writer that can do it by default?


Ext.define('Groups', {
extend: 'Ext.data.Model',
fields: [
{ name: 'GroupName', type: 'string' },
{ name: 'GroupDescription', type: 'string' }
],
proxy: {
api: {
read: 'ListGroups',
destroy: 'DeleteGroup'
},
type: 'ajax',
reader: {
type: 'json',
root: 'result'
}
}
});

The default writer outputs {"GroupName": "abc", "GroupDescriptions":"desc"}, and the content-type: application/json. I want to post: GroupName=abc&GroupDescription=desc and content-type: application/x-www-form-urlencoded;

Is there a writer that can do it or do I have to code everything manually?

skirtle
9 Nov 2011, 8:25 PM
I don't think there is a writer to do that out-of-the-box but it should be pretty easy.

Take a look at the code for the Json writer, it's only a few lines:

http://docs.sencha.com/ext-js/4-0/source/Json2.html#Ext-data-writer-Json

Json writers allow you to send data as a single request parameter (encode: true), should be able to adapt that in your own writer.

One reason this isn't supported is that writers need to be able to handle multiple records at once and it isn't clear how you do that in the scenario you describe.

panpawel
10 Nov 2011, 9:37 AM
Thanks for the suggestion, Skirtle, it put me on the right track of checking the source code for Json writer. I ended up overwriting 'writeRecords' function of Ext.data.writer.Writer and assigned the writer to my proxy. It worked great, exactly what I needed.


writer: new Ext.data.writer.Writer({
writeRecords: function (request, data) {
var root = this.root;

if (data.length == 1) {
// convert to single object format and send as params
data = data[0];
Ext.apply(request.params, data);
}
else {
// send as jsonData
request.jsonData = request.jsonData || {};
if (root) {
request.jsonData[root] = data;
} else {
request.jsonData = data;
}
}
return request;
}
})