Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / widgets / form / Action.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.form.Action
9  * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p>
10  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
11  * the Form needs to perform an action such as submit or load. The Configuration options
12  * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit},
13  * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p>
14  * <p>The instance of Action which performed the action is passed to the success
15  * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit},
16  * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}),
17  * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and
18  * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p>
19  */
20 Ext.form.Action = function(form, options){
21     this.form = form;
22     this.options = options || {};
23 };
24
25 /**
26  * Failure type returned when client side validation of the Form fails
27  * thus aborting a submit action. Client side validation is performed unless
28  * {@link #clientValidation} is explicitly set to <tt>false</tt>.
29  * @type {String}
30  * @static
31  */
32 Ext.form.Action.CLIENT_INVALID = 'client';
33 /**
34  * <p>Failure type returned when server side processing fails and the {@link #result}'s
35  * <tt style="font-weight:bold">success</tt> property is set to <tt>false</tt>.</p>
36  * <p>In the case of a form submission, field-specific error messages may be returned in the
37  * {@link #result}'s <tt style="font-weight:bold">errors</tt> property.</p>
38  * @type {String}
39  * @static
40  */
41 Ext.form.Action.SERVER_INVALID = 'server';
42 /**
43  * Failure type returned when a communication error happens when attempting
44  * to send a request to the remote server. The {@link #response} may be examined to
45  * provide further information.
46  * @type {String}
47  * @static
48  */
49 Ext.form.Action.CONNECT_FAILURE = 'connect';
50 /**
51  * Failure type returned when the response's <tt style="font-weight:bold">success</tt>
52  * property is set to <tt>false</tt>, or no field values are returned in the response's
53  * <tt style="font-weight:bold">data</tt> property.
54  * @type {String}
55  * @static
56  */
57 Ext.form.Action.LOAD_FAILURE = 'load';
58
59 Ext.form.Action.prototype = {
60 /**
61  * @cfg {String} url The URL that the Action is to invoke.
62  */
63 /**
64  * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be
65  * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens
66  * <b>before</b> the {@link #success} callback is called and before the Form's
67  * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires.
68  */
69 /**
70  * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the
71  * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method.
72  */
73 /**
74  * @cfg {Mixed} params <p>Extra parameter values to pass. These are added to the Form's
75  * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's
76  * input fields.</p>
77  * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
78  */
79 /**
80  * @cfg {Number} timeout The number of seconds to wait for a server response before
81  * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. If not specified,
82  * defaults to the configured <tt>{@link Ext.form.BasicForm#timeout timeout}</tt> of the
83  * {@link Ext.form.BasicForm form}.
84  */
85 /**
86  * @cfg {Function} success The function to call when a valid success return packet is recieved.
87  * The function is passed the following parameters:<ul class="mdetail-params">
88  * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
89  * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result}
90  * property of this object may be examined to perform custom postprocessing.</div></li>
91  * </ul>
92  */
93 /**
94  * @cfg {Function} failure The function to call when a failure packet was recieved, or when an
95  * error ocurred in the Ajax communication.
96  * The function is passed the following parameters:<ul class="mdetail-params">
97  * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
98  * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax
99  * error ocurred, the failure type will be in {@link #failureType}. The {@link #result}
100  * property of this object may be examined to perform custom postprocessing.</div></li>
101  * </ul>
102  */
103 /**
104  * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference
105  * for the callback functions).
106  */
107 /**
108  * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait}
109  * during the time the action is being processed.
110  */
111 /**
112  * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait}
113  * during the time the action is being processed.
114  */
115
116 /**
117  * The type of action this Action instance performs.
118  * Currently only "submit" and "load" are supported.
119  * @type {String}
120  */
121     type : 'default',
122 /**
123  * The type of failure detected will be one of these: {@link #CLIENT_INVALID},
124  * {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}.  Usage:
125  * <pre><code>
126 var fp = new Ext.form.FormPanel({
127 ...
128 buttons: [{
129     text: 'Save',
130     formBind: true,
131     handler: function(){
132         if(fp.getForm().isValid()){
133             fp.getForm().submit({
134                 url: 'form-submit.php',
135                 waitMsg: 'Submitting your data...',
136                 success: function(form, action){
137                     // server responded with success = true
138                     var result = action.{@link #result};
139                 },
140                 failure: function(form, action){
141                     if (action.{@link #failureType} === Ext.form.Action.{@link #CONNECT_FAILURE}) {
142                         Ext.Msg.alert('Error',
143                             'Status:'+action.{@link #response}.status+': '+
144                             action.{@link #response}.statusText);
145                     }
146                     if (action.failureType === Ext.form.Action.{@link #SERVER_INVALID}){
147                         // server responded with success = false
148                         Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
149                     }
150                 }
151             });
152         }
153     }
154 },{
155     text: 'Reset',
156     handler: function(){
157         fp.getForm().reset();
158     }
159 }]
160  * </code></pre>
161  * @property failureType
162  * @type {String}
163  */
164  /**
165  * The XMLHttpRequest object used to perform the action.
166  * @property response
167  * @type {Object}
168  */
169  /**
170  * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
171  * other, action-specific properties.
172  * @property result
173  * @type {Object}
174  */
175
176     // interface method
177     run : function(options){
178
179     },
180
181     // interface method
182     success : function(response){
183
184     },
185
186     // interface method
187     handleResponse : function(response){
188
189     },
190
191     // default connection failure
192     failure : function(response){
193         this.response = response;
194         this.failureType = Ext.form.Action.CONNECT_FAILURE;
195         this.form.afterAction(this, false);
196     },
197
198     // private
199     // shared code among all Actions to validate that there was a response
200     // with either responseText or responseXml
201     processResponse : function(response){
202         this.response = response;
203         if(!response.responseText && !response.responseXML){
204             return true;
205         }
206         this.result = this.handleResponse(response);
207         return this.result;
208     },
209
210     // utility functions used internally
211     getUrl : function(appendParams){
212         var url = this.options.url || this.form.url || this.form.el.dom.action;
213         if(appendParams){
214             var p = this.getParams();
215             if(p){
216                 url = Ext.urlAppend(url, p);
217             }
218         }
219         return url;
220     },
221
222     // private
223     getMethod : function(){
224         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
225     },
226
227     // private
228     getParams : function(){
229         var bp = this.form.baseParams;
230         var p = this.options.params;
231         if(p){
232             if(typeof p == "object"){
233                 p = Ext.urlEncode(Ext.applyIf(p, bp));
234             }else if(typeof p == 'string' && bp){
235                 p += '&' + Ext.urlEncode(bp);
236             }
237         }else if(bp){
238             p = Ext.urlEncode(bp);
239         }
240         return p;
241     },
242
243     // private
244     createCallback : function(opts){
245         var opts = opts || {};
246         return {
247             success: this.success,
248             failure: this.failure,
249             scope: this,
250             timeout: (opts.timeout*1000) || (this.form.timeout*1000),
251             upload: this.form.fileUpload ? this.success : undefined
252         };
253     }
254 };
255
256 /**
257  * @class Ext.form.Action.Submit
258  * @extends Ext.form.Action
259  * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s
260  * and processes the returned response.</p>
261  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
262  * {@link Ext.form.BasicForm#submit submit}ting.</p>
263  * <p><u><b>Response Packet Criteria</b></u></p>
264  * <p>A response packet may contain:
265  * <div class="mdetail-params"><ul>
266  * <li><b><code>success</code></b> property : Boolean
267  * <div class="sub-desc">The <code>success</code> property is required.</div></li>
268  * <li><b><code>errors</code></b> property : Object
269  * <div class="sub-desc"><div class="sub-desc">The <code>errors</code> property,
270  * which is optional, contains error messages for invalid fields.</div></li>
271  * </ul></div>
272  * <p><u><b>JSON Packets</b></u></p>
273  * <p>By default, response packets are assumed to be JSON, so a typical response
274  * packet may look like this:</p><pre><code>
275 {
276     success: false,
277     errors: {
278         clientCode: "Client not found",
279         portOfLoading: "This field must not be null"
280     }
281 }</code></pre>
282  * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback
283  * or event handler methods. The object decoded from this JSON is available in the
284  * {@link Ext.form.Action#result result} property.</p>
285  * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>
286     errorReader: new Ext.data.XmlReader({
287             record : 'field',
288             success: '@success'
289         }, [
290             'id', 'msg'
291         ]
292     )
293 </code></pre>
294  * <p>then the results may be sent back in XML format:</p><pre><code>
295 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
296 &lt;message success="false"&gt;
297 &lt;errors&gt;
298     &lt;field&gt;
299         &lt;id&gt;clientCode&lt;/id&gt;
300         &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;
301     &lt;/field&gt;
302     &lt;field&gt;
303         &lt;id&gt;portOfLoading&lt;/id&gt;
304         &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;
305     &lt;/field&gt;
306 &lt;/errors&gt;
307 &lt;/message&gt;
308 </code></pre>
309  * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback
310  * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>
311  */
312 Ext.form.Action.Submit = function(form, options){
313     Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
314 };
315
316 Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
317     /**
318      * @cfg {Ext.data.DataReader} errorReader <p><b>Optional. JSON is interpreted with
319      * no need for an errorReader.</b></p>
320      * <p>A Reader which reads a single record from the returned data. The DataReader's
321      * <b>success</b> property specifies how submission success is determined. The Record's
322      * data provides the error messages to apply to any invalid form Fields.</p>
323      */
324     /**
325      * @cfg {boolean} clientValidation Determines whether a Form's fields are validated
326      * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.
327      * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation
328      * is performed.
329      */
330     type : 'submit',
331
332     // private
333     run : function(){
334         var o = this.options;
335         var method = this.getMethod();
336         var isGet = method == 'GET';
337         if(o.clientValidation === false || this.form.isValid()){
338             Ext.Ajax.request(Ext.apply(this.createCallback(o), {
339                 form:this.form.el.dom,
340                 url:this.getUrl(isGet),
341                 method: method,
342                 headers: o.headers,
343                 params:!isGet ? this.getParams() : null,
344                 isUpload: this.form.fileUpload
345             }));
346         }else if (o.clientValidation !== false){ // client validation failed
347             this.failureType = Ext.form.Action.CLIENT_INVALID;
348             this.form.afterAction(this, false);
349         }
350     },
351
352     // private
353     success : function(response){
354         var result = this.processResponse(response);
355         if(result === true || result.success){
356             this.form.afterAction(this, true);
357             return;
358         }
359         if(result.errors){
360             this.form.markInvalid(result.errors);
361             this.failureType = Ext.form.Action.SERVER_INVALID;
362         }
363         this.form.afterAction(this, false);
364     },
365
366     // private
367     handleResponse : function(response){
368         if(this.form.errorReader){
369             var rs = this.form.errorReader.read(response);
370             var errors = [];
371             if(rs.records){
372                 for(var i = 0, len = rs.records.length; i < len; i++) {
373                     var r = rs.records[i];
374                     errors[i] = r.data;
375                 }
376             }
377             if(errors.length < 1){
378                 errors = null;
379             }
380             return {
381                 success : rs.success,
382                 errors : errors
383             };
384         }
385         return Ext.decode(response.responseText);
386     }
387 });
388
389
390 /**
391  * @class Ext.form.Action.Load
392  * @extends Ext.form.Action
393  * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
394  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
395  * {@link Ext.form.BasicForm#load load}ing.</p>
396  * <p><u><b>Response Packet Criteria</b></u></p>
397  * <p>A response packet <b>must</b> contain:
398  * <div class="mdetail-params"><ul>
399  * <li><b><code>success</code></b> property : Boolean</li>
400  * <li><b><code>data</code></b> property : Object</li>
401  * <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
402  * The individual value object for each Field is passed to the Field's
403  * {@link Ext.form.Field#setValue setValue} method.</div></li>
404  * </ul></div>
405  * <p><u><b>JSON Packets</b></u></p>
406  * <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
407 var myFormPanel = new Ext.form.FormPanel({
408     title: 'Client and routing info',
409     items: [{
410         fieldLabel: 'Client',
411         name: 'clientName'
412     }, {
413         fieldLabel: 'Port of loading',
414         name: 'portOfLoading'
415     }, {
416         fieldLabel: 'Port of discharge',
417         name: 'portOfDischarge'
418     }]
419 });
420 myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
421     url: '/getRoutingInfo.php',
422     params: {
423         consignmentRef: myConsignmentRef
424     },
425     failure: function(form, action() {
426         Ext.Msg.alert("Load failed", action.result.errorMessage);
427     }
428 });
429 </code></pre>
430  * a <b>success response</b> packet may look like this:</p><pre><code>
431 {
432     success: true,
433     data: {
434         clientName: "Fred. Olsen Lines",
435         portOfLoading: "FXT",
436         portOfDischarge: "OSL"
437     }
438 }</code></pre>
439  * while a <b>failure response</b> packet may look like this:</p><pre><code>
440 {
441     success: false,
442     errorMessage: "Consignment reference not found"
443 }</code></pre>
444  * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s
445  * callback or event handler methods. The object decoded from this JSON is available in the
446  * {@link Ext.form.Action#result result} property.</p>
447  */
448 Ext.form.Action.Load = function(form, options){
449     Ext.form.Action.Load.superclass.constructor.call(this, form, options);
450     this.reader = this.form.reader;
451 };
452
453 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
454     // private
455     type : 'load',
456
457     // private
458     run : function(){
459         Ext.Ajax.request(Ext.apply(
460                 this.createCallback(this.options), {
461                     method:this.getMethod(),
462                     url:this.getUrl(false),
463                     headers: this.options.headers,
464                     params:this.getParams()
465         }));
466     },
467
468     // private
469     success : function(response){
470         var result = this.processResponse(response);
471         if(result === true || !result.success || !result.data){
472             this.failureType = Ext.form.Action.LOAD_FAILURE;
473             this.form.afterAction(this, false);
474             return;
475         }
476         this.form.clearInvalid();
477         this.form.setValues(result.data);
478         this.form.afterAction(this, true);
479     },
480
481     // private
482     handleResponse : function(response){
483         if(this.form.reader){
484             var rs = this.form.reader.read(response);
485             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
486             return {
487                 success : rs.success,
488                 data : data
489             };
490         }
491         return Ext.decode(response.responseText);
492     }
493 });
494
495
496
497 /**
498  * @class Ext.form.Action.DirectLoad
499  * @extends Ext.form.Action.Load
500  * Provides Ext.direct support for loading form data. This example illustrates usage
501  * of Ext.Direct to load a submit a form through Ext.Direct.
502  * <pre><code>
503 var myFormPanel = new Ext.form.FormPanel({
504     // configs for FormPanel
505     title: 'Basic Information',
506     border: false,
507     padding: 10,
508     buttons:[{
509         text: 'Submit',
510         handler: function(){
511             basicInfo.getForm().submit({
512                 params: {
513                     uid: 5
514                 }
515             });
516         }
517     }],
518     
519     // configs apply to child items
520     defaults: {anchor: '100%'},
521     defaultType: 'textfield',
522     items: [
523         // form fields go here
524     ],
525     
526     // configs for BasicForm
527     api: {
528         load: Profile.getBasicInfo,
529         // The server-side must mark the submit handler as a 'formHandler'
530         submit: Profile.updateBasicInfo
531     },    
532     paramOrder: ['uid']
533 });
534
535 // load the form
536 myFormPanel.getForm().load({
537     params: {
538         uid: 5
539     }
540 });
541  * </code></pre>
542  */
543 Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
544     constructor: function(form, opts) {        
545         Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
546     },
547     type: 'directload',
548     
549     run : function(){
550         var args = this.getParams();
551         args.push(this.success, this);                
552         this.form.api.load.apply(window, args);
553     },
554     
555     getParams: function() {
556         var buf = [], o = {};
557         var bp = this.form.baseParams;
558         var p = this.options.params;
559         Ext.apply(o, p, bp);
560         var paramOrder = this.form.paramOrder;
561         if(paramOrder){
562             for(var i = 0, len = paramOrder.length; i < len; i++){
563                 buf.push(o[paramOrder[i]]);
564             }
565         }else if(this.form.paramsAsHash){
566             buf.push(o);
567         }
568         return buf;
569     },
570     // Direct actions have already been processed and therefore
571     // we can directly set the result; Direct Actions do not have
572     // a this.response property.
573     processResponse: function(result) {
574         this.result = result;
575         return result;          
576     }
577 });
578
579 /**
580  * @class Ext.form.Action.DirectSubmit
581  * @extends Ext.form.Action.Submit
582  * Provides Ext.direct support for submitting form data.
583  * See {@link Ext.form.Action.DirectLoad}.
584  */
585 Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
586     constructor: function(form, opts) {
587         Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
588     },
589     type: 'directsubmit',
590     // override of Submit
591     run : function(){
592         var o = this.options;
593         if(o.clientValidation === false || this.form.isValid()){
594             // tag on any additional params to be posted in the
595             // form scope
596             this.success.params = this.getParams();
597             this.form.api.submit(this.form.el.dom, this.success, this);
598         }else if (o.clientValidation !== false){ // client validation failed
599             this.failureType = Ext.form.Action.CLIENT_INVALID;
600             this.form.afterAction(this, false);
601         }
602     },
603     
604     getParams: function() {
605         var o = {};
606         var bp = this.form.baseParams;
607         var p = this.options.params;
608         Ext.apply(o, p, bp);
609         return o;
610     },    
611     // Direct actions have already been processed and therefore
612     // we can directly set the result; Direct Actions do not have
613     // a this.response property.
614     processResponse: function(result) {
615         this.result = result;
616         return result;          
617     }
618 });
619
620
621 Ext.form.Action.ACTION_TYPES = {
622     'load' : Ext.form.Action.Load,
623     'submit' : Ext.form.Action.Submit,
624     'directload': Ext.form.Action.DirectLoad,
625     'directsubmit': Ext.form.Action.DirectSubmit
626 };