简体   繁体   中英

How do I change the .save() JSON output for ExtJS 4.2

I have a problem save data to my database using an ExtJS updateable grid. I'm working with a REST API that I have written in Progress ABL. The API is working but the Input JSON and Output JSON is very specific.

I can read the JSON data into my grid and display it, but when I want to save a new record the grid creates a wrong JSON output.

My output has to be like this:

   {
      "request":
        {
          "dsUsers":
            {
              "ttUsers":
                [{"ID":20,"LOGIN":"test","PASS":"","ID_ADDR":0,"ID_CUST":0}]
            }
        }
    }

But I'm not able to create the request and dsUsers groups in the writer. I have tested a lot but I don't really know what I have to change to make it work.

Thanks

Base Ext.data.writer.Json allows you to define only root data property. However if you need more custom structure like this, you can quite easily create your own writer.

Your writer should extend from Ext.data.writer.Json and override writeRecords method. This method add records data into request.

In your case custom writer should look like this:

Ext.define('myWriter', {
    extend: 'Ext.data.writer.Json',
    writeRecords: function(request, data) {
        var root = this.root;        

        if (this.expandData) {
            data = this.getExpandedData(data);
        }

        if (this.allowSingle && data.length === 1) {
            // convert to single object format
            data = data[0];
        }

        request.jsonData = request.jsonData || {};
        request.jsonData['request'] = {
            'dsUsers': {}
        };

        request.jsonData['request']['dsUsers'][root] = data;

        return request;
    }    
});

Then you can use your custom writer in model or store proxy:

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'email'],
    proxy: {
        type: 'rest',
        writer: Ext.create('myWriter', {
            root: 'ttUsers',
            mainRoot: 'dsUsers'
        }),
        url : '/users'
    }            
});

Of course you can create custom writer more configurable and reusable by defining name of "request" and "dsUsers" attributes in config.

Fiddle with example: https://fiddle.sencha.com/#fiddle/33l

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM