commit extjs-2.2.1
[extjs.git] / source / widgets / form / Action.js
1 /*\r
2  * Ext JS Library 2.2.1\r
3  * Copyright(c) 2006-2009, Ext JS, LLC.\r
4  * licensing@extjs.com\r
5  * \r
6  * http://extjs.com/license\r
7  */\r
8 \r
9 /**\r
10  * @class Ext.form.Action\r
11  * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p>\r
12  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when\r
13  * the Form needs to perform an action such as submit or load. The Configuration options\r
14  * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit},\r
15  * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p>\r
16  * <p>The instance of Action which performed the action is passed to the success\r
17  * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit},\r
18  * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}),\r
19  * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and\r
20  * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p>\r
21  */\r
22 Ext.form.Action = function(form, options){\r
23     this.form = form;\r
24     this.options = options || {};\r
25 };\r
26 \r
27 /**\r
28  * Failure type returned when client side validation of the Form fails\r
29  * thus aborting a submit action.\r
30  * @type {String}\r
31  * @static\r
32  */\r
33 Ext.form.Action.CLIENT_INVALID = 'client';\r
34 /**\r
35  * Failure type returned when server side validation of the Form fails\r
36  * indicating that field-specific error messages have been returned in the\r
37  * response's <tt style="font-weight:bold">errors</tt> property.\r
38  * @type {String}\r
39  * @static\r
40  */\r
41 Ext.form.Action.SERVER_INVALID = 'server';\r
42 /**\r
43  * Failure type returned when a communication error happens when attempting\r
44  * to send a request to the remote server.\r
45  * @type {String}\r
46  * @static\r
47  */\r
48 Ext.form.Action.CONNECT_FAILURE = 'connect';\r
49 /**\r
50  * Failure type returned when no field values are returned in the response's\r
51  * <tt style="font-weight:bold">data</tt> property.\r
52  * @type {String}\r
53  * @static\r
54  */\r
55 Ext.form.Action.LOAD_FAILURE = 'load';\r
56 \r
57 Ext.form.Action.prototype = {\r
58 /**\r
59  * @cfg {String} url The URL that the Action is to invoke.\r
60  */\r
61 /**\r
62  * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be\r
63  * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens\r
64  * <b>before</b> the {@link #success} callback is called and before the Form's\r
65  * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires.\r
66  */\r
67 /**\r
68  * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the\r
69  * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method.\r
70  */\r
71 /**\r
72  * @cfg {Mixed} params Extra parameter values to pass. These are added to the Form's\r
73  * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's\r
74  * input fields.\r
75  */\r
76 /**\r
77  * @cfg {Number} timeout The number of milliseconds to wait for a server response before\r
78  * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}.\r
79  */\r
80 /**\r
81  * @cfg {Function} success The function to call when a valid success return packet is recieved.\r
82  * The function is passed the following parameters:<ul class="mdetail-params">\r
83  * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>\r
84  * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result}\r
85  * property of this object may be examined to perform custom postprocessing.</div></li>\r
86  * </ul>\r
87  */\r
88 /**\r
89  * @cfg {Function} failure The function to call when a failure packet was recieved, or when an\r
90  * error ocurred in the Ajax communication.\r
91  * The function is passed the following parameters:<ul class="mdetail-params">\r
92  * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>\r
93  * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax\r
94  * error ocurred, the failure type will be in {@link #failureType}. The {@link #result}\r
95  * property of this object may be examined to perform custom postprocessing.</div></li>\r
96  * </ul>\r
97 */\r
98 /**\r
99  * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference\r
100  * for the callback functions).\r
101  */\r
102 /**\r
103  * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait}\r
104  * during the time the action is being processed.\r
105  */\r
106 /**\r
107  * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait}\r
108  * during the time the action is being processed.\r
109  */\r
110 \r
111 /**\r
112  * The type of action this Action instance performs.\r
113  * Currently only "submit" and "load" are supported.\r
114  * @type {String}\r
115  */\r
116     type : 'default',\r
117 /**\r
118  * The type of failure detected. See {@link link Ext.form.Action#Action.CLIENT_INVALID CLIENT_INVALID},\r
119  * {@link link Ext.form.Action#Action.SERVER_INVALID SERVER_INVALID},\r
120  * {@link #link Ext.form.ActionAction.CONNECT_FAILURE CONNECT_FAILURE}, {@link Ext.form.Action#Action.LOAD_FAILURE LOAD_FAILURE}\r
121  * @property failureType\r
122  * @type {String}\r
123  *//**\r
124  * The XMLHttpRequest object used to perform the action.\r
125  * @property response\r
126  * @type {Object}\r
127  *//**\r
128  * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and\r
129  * other, action-specific properties.\r
130  * @property result\r
131  * @type {Object}\r
132  */\r
133 \r
134     // interface method\r
135     run : function(options){\r
136 \r
137     },\r
138 \r
139     // interface method\r
140     success : function(response){\r
141 \r
142     },\r
143 \r
144     // interface method\r
145     handleResponse : function(response){\r
146 \r
147     },\r
148 \r
149     // default connection failure\r
150     failure : function(response){\r
151         this.response = response;\r
152         this.failureType = Ext.form.Action.CONNECT_FAILURE;\r
153         this.form.afterAction(this, false);\r
154     },\r
155 \r
156     // private\r
157     processResponse : function(response){\r
158         this.response = response;\r
159         if(!response.responseText){\r
160             return true;\r
161         }\r
162         this.result = this.handleResponse(response);\r
163         return this.result;\r
164     },\r
165 \r
166     // utility functions used internally\r
167     getUrl : function(appendParams){\r
168         var url = this.options.url || this.form.url || this.form.el.dom.action;\r
169         if(appendParams){\r
170             var p = this.getParams();\r
171             if(p){\r
172                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;\r
173             }\r
174         }\r
175         return url;\r
176     },\r
177 \r
178     // private\r
179     getMethod : function(){\r
180         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();\r
181     },\r
182 \r
183     // private\r
184     getParams : function(){\r
185         var bp = this.form.baseParams;\r
186         var p = this.options.params;\r
187         if(p){\r
188             if(typeof p == "object"){\r
189                 p = Ext.urlEncode(Ext.applyIf(p, bp));\r
190             }else if(typeof p == 'string' && bp){\r
191                 p += '&' + Ext.urlEncode(bp);\r
192             }\r
193         }else if(bp){\r
194             p = Ext.urlEncode(bp);\r
195         }\r
196         return p;\r
197     },\r
198 \r
199     // private\r
200     createCallback : function(opts){\r
201                 var opts = opts || {};\r
202         return {\r
203             success: this.success,\r
204             failure: this.failure,\r
205             scope: this,\r
206             timeout: (opts.timeout*1000) || (this.form.timeout*1000),\r
207             upload: this.form.fileUpload ? this.success : undefined\r
208         };\r
209     }\r
210 };\r
211 \r
212 /**\r
213  * @class Ext.form.Action.Submit\r
214  * @extends Ext.form.Action\r
215  * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s\r
216  * and processes the returned response.</p>\r
217  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when\r
218  * {@link Ext.form.BasicForm#submit submit}ting.</p>\r
219  * <p>A response packet must contain a boolean <tt style="font-weight:bold">success</tt> property, and, optionally\r
220  * an <tt style="font-weight:bold">errors</tt> property. The <tt style="font-weight:bold">errors</tt> property contains error\r
221  * messages for invalid fields.</p>\r
222  * <p>By default, response packets are assumed to be JSON, so a typical response\r
223  * packet may look like this:</p><pre><code>\r
224 {\r
225     success: false,\r
226     errors: {\r
227         clientCode: "Client not found",\r
228         portOfLoading: "This field must not be null"\r
229     }\r
230 }</code></pre>\r
231  * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback\r
232  * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p>\r
233  * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>\r
234     errorReader: new Ext.data.XmlReader({\r
235             record : 'field',\r
236             success: '@success'\r
237         }, [\r
238             'id', 'msg'\r
239         ]\r
240     )\r
241 </code></pre>\r
242  * <p>then the results may be sent back in XML format:</p><pre><code>\r
243 &lt;?xml version="1.0" encoding="UTF-8"?&gt;\r
244 &lt;message success="false"&gt;\r
245 &lt;errors&gt;\r
246     &lt;field&gt;\r
247         &lt;id&gt;clientCode&lt;/id&gt;\r
248         &lt;msg&gt;&lt;![CDATA[Code not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt;\r
249     &lt;/field&gt;\r
250     &lt;field&gt;\r
251         &lt;id&gt;portOfLoading&lt;/id&gt;\r
252         &lt;msg&gt;&lt;![CDATA[Port not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt;\r
253     &lt;/field&gt;\r
254 &lt;/errors&gt;\r
255 &lt;/message&gt;\r
256 </code></pre>\r
257  * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback\r
258  * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>\r
259  */\r
260 Ext.form.Action.Submit = function(form, options){\r
261     Ext.form.Action.Submit.superclass.constructor.call(this, form, options);\r
262 };\r
263 \r
264 Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {\r
265     /**\r
266     * @cfg {Ext.data.DataReader} errorReader <b>Optional. JSON is interpreted with no need for an errorReader.</b>\r
267     * <p>A Reader which reads a single record from the returned data. The DataReader's <b>success</b> property specifies\r
268     * how submission success is determined. The Record's data provides the error messages to apply to any invalid form Fields.</p>.\r
269     */\r
270     /**\r
271     * @cfg {boolean} clientValidation Determines whether a Form's fields are validated\r
272     * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.\r
273     * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation\r
274     * is performed.\r
275     */\r
276     type : 'submit',\r
277 \r
278     // private\r
279     run : function(){\r
280         var o = this.options;\r
281         var method = this.getMethod();\r
282         var isGet = method == 'GET';\r
283         if(o.clientValidation === false || this.form.isValid()){\r
284             Ext.Ajax.request(Ext.apply(this.createCallback(o), {\r
285                 form:this.form.el.dom,\r
286                 url:this.getUrl(isGet),\r
287                 method: method,\r
288                 headers: o.headers,\r
289                 params:!isGet ? this.getParams() : null,\r
290                 isUpload: this.form.fileUpload\r
291             }));\r
292         }else if (o.clientValidation !== false){ // client validation failed\r
293             this.failureType = Ext.form.Action.CLIENT_INVALID;\r
294             this.form.afterAction(this, false);\r
295         }\r
296     },\r
297 \r
298     // private\r
299     success : function(response){\r
300         var result = this.processResponse(response);\r
301         if(result === true || result.success){\r
302             this.form.afterAction(this, true);\r
303             return;\r
304         }\r
305         if(result.errors){\r
306             this.form.markInvalid(result.errors);\r
307             this.failureType = Ext.form.Action.SERVER_INVALID;\r
308         }\r
309         this.form.afterAction(this, false);\r
310     },\r
311 \r
312     // private\r
313     handleResponse : function(response){\r
314         if(this.form.errorReader){\r
315             var rs = this.form.errorReader.read(response);\r
316             var errors = [];\r
317             if(rs.records){\r
318                 for(var i = 0, len = rs.records.length; i < len; i++) {\r
319                     var r = rs.records[i];\r
320                     errors[i] = r.data;\r
321                 }\r
322             }\r
323             if(errors.length < 1){\r
324                 errors = null;\r
325             }\r
326             return {\r
327                 success : rs.success,\r
328                 errors : errors\r
329             };\r
330         }\r
331         return Ext.decode(response.responseText);\r
332     }\r
333 });\r
334 \r
335 \r
336 /**\r
337  * @class Ext.form.Action.Load\r
338  * @extends Ext.form.Action\r
339  * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>\r
340  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when\r
341  * {@link Ext.form.BasicForm#load load}ing.</p>\r
342  * <p>A response packet <b>must</b> contain a boolean <tt style="font-weight:bold">success</tt> property, and\r
343  * a <tt style="font-weight:bold">data</tt> property. The <tt style="font-weight:bold">data</tt> property\r
344  * contains the values of Fields to load. The individual value object for each Field\r
345  * is passed to the Field's {@link Ext.form.Field#setValue setValue} method.</p>\r
346  * <p>By default, response packets are assumed to be JSON, so a typical response\r
347  * packet may look like this:</p><pre><code>\r
348 {\r
349     success: true,\r
350     data: {\r
351         clientName: "Fred. Olsen Lines",\r
352         portOfLoading: "FXT",\r
353         portOfDischarge: "OSL"\r
354     }\r
355 }</code></pre>\r
356  * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s callback\r
357  * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p>\r
358  */\r
359 Ext.form.Action.Load = function(form, options){\r
360     Ext.form.Action.Load.superclass.constructor.call(this, form, options);\r
361     this.reader = this.form.reader;\r
362 };\r
363 \r
364 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {\r
365     // private\r
366     type : 'load',\r
367 \r
368     // private\r
369     run : function(){\r
370         Ext.Ajax.request(Ext.apply(\r
371                 this.createCallback(this.options), {\r
372                     method:this.getMethod(),\r
373                     url:this.getUrl(false),\r
374                     headers: this.options.headers,\r
375                     params:this.getParams()\r
376         }));\r
377     },\r
378 \r
379     // private\r
380     success : function(response){\r
381         var result = this.processResponse(response);\r
382         if(result === true || !result.success || !result.data){\r
383             this.failureType = Ext.form.Action.LOAD_FAILURE;\r
384             this.form.afterAction(this, false);\r
385             return;\r
386         }\r
387         this.form.clearInvalid();\r
388         this.form.setValues(result.data);\r
389         this.form.afterAction(this, true);\r
390     },\r
391 \r
392     // private\r
393     handleResponse : function(response){\r
394         if(this.form.reader){\r
395             var rs = this.form.reader.read(response);\r
396             var data = rs.records && rs.records[0] ? rs.records[0].data : null;\r
397             return {\r
398                 success : rs.success,\r
399                 data : data\r
400             };\r
401         }\r
402         return Ext.decode(response.responseText);\r
403     }\r
404 });\r
405 \r
406 Ext.form.Action.ACTION_TYPES = {\r
407     'load' : Ext.form.Action.Load,\r
408     'submit' : Ext.form.Action.Submit\r
409 };\r