3 * Copyright(c) 2006-2010 Ext JS, LLC
5 * http://www.extjs.com/license
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>
20 Ext.form.Action = function(form, options){
22 this.options = options || {};
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>.
32 Ext.form.Action.CLIENT_INVALID = 'client';
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>
41 Ext.form.Action.SERVER_INVALID = 'server';
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.
49 Ext.form.Action.CONNECT_FAILURE = 'connect';
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.
57 Ext.form.Action.LOAD_FAILURE = 'load';
59 Ext.form.Action.prototype = {
61 * @cfg {String} url The URL that the Action is to invoke.
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.
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.
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
77 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
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}.
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>
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>
104 * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference
105 * for the callback functions).
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.
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.
117 * The type of action this Action instance performs.
118 * Currently only "submit" and "load" are supported.
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:
126 var fp = new Ext.form.FormPanel({
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};
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);
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);
157 fp.getForm().reset();
161 * @property failureType
165 * The XMLHttpRequest object used to perform the action.
170 * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
171 * other, action-specific properties.
177 run : function(options){
182 success : function(response){
187 handleResponse : function(response){
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);
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){
206 this.result = this.handleResponse(response);
210 // utility functions used internally
211 getUrl : function(appendParams){
212 var url = this.options.url || this.form.url || this.form.el.dom.action;
214 var p = this.getParams();
216 url = Ext.urlAppend(url, p);
223 getMethod : function(){
224 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
228 getParams : function(){
229 var bp = this.form.baseParams;
230 var p = this.options.params;
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);
238 p = Ext.urlEncode(bp);
244 createCallback : function(opts){
245 var opts = opts || {};
247 success: this.success,
248 failure: this.failure,
250 timeout: (opts.timeout*1000) || (this.form.timeout*1000),
251 upload: this.form.fileUpload ? this.success : undefined
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>
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>
278 clientCode: "Client not found",
279 portOfLoading: "This field must not be null"
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({
294 * <p>then the results may be sent back in XML format:</p><pre><code>
295 <?xml version="1.0" encoding="UTF-8"?>
296 <message success="false">
299 <id>clientCode</id>
300 <msg><![CDATA[Code not found. <br /><i>This is a test validation message from the server </i>]]></msg>
303 <id>portOfLoading</id>
304 <msg><![CDATA[Port not found. <br /><i>This is a test validation message from the server </i>]]></msg>
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>
312 Ext.form.Action.Submit = function(form, options){
313 Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
316 Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
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>
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
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),
343 params:!isGet ? this.getParams() : null,
344 isUpload: this.form.fileUpload
346 }else if (o.clientValidation !== false){ // client validation failed
347 this.failureType = Ext.form.Action.CLIENT_INVALID;
348 this.form.afterAction(this, false);
353 success : function(response){
354 var result = this.processResponse(response);
355 if(result === true || result.success){
356 this.form.afterAction(this, true);
360 this.form.markInvalid(result.errors);
362 this.failureType = Ext.form.Action.SERVER_INVALID;
363 this.form.afterAction(this, false);
367 handleResponse : function(response){
368 if(this.form.errorReader){
369 var rs = this.form.errorReader.read(response);
372 for(var i = 0, len = rs.records.length; i < len; i++) {
373 var r = rs.records[i];
377 if(errors.length < 1){
381 success : rs.success,
385 return Ext.decode(response.responseText);
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>
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',
410 fieldLabel: 'Client',
413 fieldLabel: 'Port of loading',
414 name: 'portOfLoading'
416 fieldLabel: 'Port of discharge',
417 name: 'portOfDischarge'
420 myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
421 url: '/getRoutingInfo.php',
423 consignmentRef: myConsignmentRef
425 failure: function(form, action) {
426 Ext.Msg.alert("Load failed", action.result.errorMessage);
430 * a <b>success response</b> packet may look like this:</p><pre><code>
434 clientName: "Fred. Olsen Lines",
435 portOfLoading: "FXT",
436 portOfDischarge: "OSL"
439 * while a <b>failure response</b> packet may look like this:</p><pre><code>
442 errorMessage: "Consignment reference not found"
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>
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;
453 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
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()
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);
476 this.form.clearInvalid();
477 this.form.setValues(result.data);
478 this.form.afterAction(this, true);
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;
487 success : rs.success,
491 return Ext.decode(response.responseText);
498 * @class Ext.form.Action.DirectLoad
499 * @extends Ext.form.Action.Load
500 * <p>Provides Ext.direct support for loading form data.</p>
501 * <p>This example illustrates usage of Ext.Direct to <b>load</b> a form through Ext.Direct.</p>
503 var myFormPanel = new Ext.form.FormPanel({
504 // configs for FormPanel
505 title: 'Basic Information',
506 renderTo: document.body,
507 width: 300, height: 160,
510 // configs apply to child items
511 defaults: {anchor: '100%'},
512 defaultType: 'textfield',
520 fieldLabel: 'Company',
524 // configs for BasicForm
526 // The server-side method to call for load() requests
527 load: Profile.getBasicInfo,
528 // The server-side must mark the submit handler as a 'formHandler'
529 submit: Profile.updateBasicInfo
531 // specify the order for the passed params
532 paramOrder: ['uid', 'foo']
536 myFormPanel.getForm().load({
537 // pass 2 arguments to server side getBasicInfo method (len=2)
544 * The data packet sent to the server will resemble something like:
548 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
549 "data":[34,"bar"] // note the order of the params
553 * The form will process a data packet returned by the server that is similar
554 * to the following format:
558 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
562 "name":"Fred Flintstone",
563 "company":"Slate Rock and Gravel",
564 "email":"fred.flintstone@slaterg.com"
571 Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
572 constructor: function(form, opts) {
573 Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
578 var args = this.getParams();
579 args.push(this.success, this);
580 this.form.api.load.apply(window, args);
583 getParams : function() {
584 var buf = [], o = {};
585 var bp = this.form.baseParams;
586 var p = this.options.params;
588 var paramOrder = this.form.paramOrder;
590 for(var i = 0, len = paramOrder.length; i < len; i++){
591 buf.push(o[paramOrder[i]]);
593 }else if(this.form.paramsAsHash){
598 // Direct actions have already been processed and therefore
599 // we can directly set the result; Direct Actions do not have
600 // a this.response property.
601 processResponse : function(result) {
602 this.result = result;
606 success : function(response, trans){
607 if(trans.type == Ext.Direct.exceptions.SERVER){
610 Ext.form.Action.DirectLoad.superclass.success.call(this, response);
615 * @class Ext.form.Action.DirectSubmit
616 * @extends Ext.form.Action.Submit
617 * <p>Provides Ext.direct support for submitting form data.</p>
618 * <p>This example illustrates usage of Ext.Direct to <b>submit</b> a form through Ext.Direct.</p>
620 var myFormPanel = new Ext.form.FormPanel({
621 // configs for FormPanel
622 title: 'Basic Information',
623 renderTo: document.body,
624 width: 300, height: 160,
629 myFormPanel.getForm().submit({
638 // configs apply to child items
639 defaults: {anchor: '100%'},
640 defaultType: 'textfield',
648 fieldLabel: 'Company',
652 // configs for BasicForm
654 // The server-side method to call for load() requests
655 load: Profile.getBasicInfo,
656 // The server-side must mark the submit handler as a 'formHandler'
657 submit: Profile.updateBasicInfo
659 // specify the order for the passed params
660 paramOrder: ['uid', 'foo']
663 * The data packet sent to the server will resemble something like:
666 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
670 "extAction":"Profile","extMethod":"updateBasicInfo",
671 "extType":"rpc","extTID":"6","extUpload":"false",
672 "name":"Aaron Conran","email":"aaron@extjs.com","company":"Ext JS, LLC"
677 * The form will process a data packet returned by the server that is similar
680 // sample success packet (batched requests)
683 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
690 // sample failure packet (one request)
692 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
695 "email":"already taken"
702 * Also see the discussion in {@link Ext.form.Action.DirectLoad}.
704 Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
705 constructor : function(form, opts) {
706 Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
708 type : 'directsubmit',
709 // override of Submit
711 var o = this.options;
712 if(o.clientValidation === false || this.form.isValid()){
713 // tag on any additional params to be posted in the
715 this.success.params = this.getParams();
716 this.form.api.submit(this.form.el.dom, this.success, this);
717 }else if (o.clientValidation !== false){ // client validation failed
718 this.failureType = Ext.form.Action.CLIENT_INVALID;
719 this.form.afterAction(this, false);
723 getParams : function() {
725 var bp = this.form.baseParams;
726 var p = this.options.params;
730 // Direct actions have already been processed and therefore
731 // we can directly set the result; Direct Actions do not have
732 // a this.response property.
733 processResponse : function(result) {
734 this.result = result;
738 success : function(response, trans){
739 if(trans.type == Ext.Direct.exceptions.SERVER){
742 Ext.form.Action.DirectSubmit.superclass.success.call(this, response);
746 Ext.form.Action.ACTION_TYPES = {
747 'load' : Ext.form.Action.Load,
748 'submit' : Ext.form.Action.Submit,
749 'directload' : Ext.form.Action.DirectLoad,
750 'directsubmit' : Ext.form.Action.DirectSubmit