Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / data / writer / Json.js
1 /**
2  * @class Ext.data.writer.Json
3  * @extends Ext.data.writer.Writer
4
5 This class is used to write {@link Ext.data.Model} data to the server in a JSON format.
6 The {@link #allowSingle} configuration can be set to false to force the records to always be
7 encoded in an array, even if there is only a single record being sent.
8
9  * @markdown
10  */
11 Ext.define('Ext.data.writer.Json', {
12     extend: 'Ext.data.writer.Writer',
13     alternateClassName: 'Ext.data.JsonWriter',
14     alias: 'writer.json',
15     
16     /**
17      * @cfg {String} root The key under which the records in this Writer will be placed. Defaults to <tt>undefined</tt>.
18      * Example generated request, using root: 'records':
19 <pre><code>
20 {'records': [{name: 'my record'}, {name: 'another record'}]}
21 </code></pre>
22      */
23     root: undefined,
24     
25     /**
26      * @cfg {Boolean} encode True to use Ext.encode() on the data before sending. Defaults to <tt>false</tt>.
27      * The encode option should only be set to true when a {@link #root} is defined, because the values will be
28      * sent as part of the request parameters as opposed to a raw post. The root will be the name of the parameter
29      * sent to the server.
30      */
31     encode: false,
32     
33     /**
34      * @cfg {Boolean} allowSingle False to ensure that records are always wrapped in an array, even if there is only
35      * one record being sent. When there is more than one record, they will always be encoded into an array.
36      * Defaults to <tt>true</tt>. Example:
37      * <pre><code>
38 // with allowSingle: true
39 "root": {
40     "first": "Mark",
41     "last": "Corrigan"
42 }
43
44 // with allowSingle: false
45 "root": [{
46     "first": "Mark",
47     "last": "Corrigan"
48 }]
49      * </code></pre>
50      */
51     allowSingle: true,
52     
53     //inherit docs
54     writeRecords: function(request, data) {
55         var root = this.root;
56         
57         if (this.allowSingle && data.length == 1) {
58             // convert to single object format
59             data = data[0];
60         }
61         
62         if (this.encode) {
63             if (root) {
64                 // sending as a param, need to encode
65                 request.params[root] = Ext.encode(data);
66             } else {
67                 //<debug>
68                 Ext.Error.raise('Must specify a root when using encode');
69                 //</debug>
70             }
71         } else {
72             // send as jsonData
73             request.jsonData = request.jsonData || {};
74             if (root) {
75                 request.jsonData[root] = data;
76             } else {
77                 request.jsonData = data;
78             }
79         }
80         return request;
81     }
82 });