3 * Copyright(c) 2006-2010 Ext JS, Inc.
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 * @cfg {Boolean} submitEmptyText If set to <tt>true</tt>, the emptyText value will be sent with the form
118 * when it is submitted. Defaults to <tt>true</tt>.
122 * The type of action this Action instance performs.
123 * Currently only "submit" and "load" are supported.
128 * The type of failure detected will be one of these: {@link #CLIENT_INVALID},
129 * {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}. Usage:
131 var fp = new Ext.form.FormPanel({
137 if(fp.getForm().isValid()){
138 fp.getForm().submit({
139 url: 'form-submit.php',
140 waitMsg: 'Submitting your data...',
141 success: function(form, action){
142 // server responded with success = true
143 var result = action.{@link #result};
145 failure: function(form, action){
146 if (action.{@link #failureType} === Ext.form.Action.{@link #CONNECT_FAILURE}) {
147 Ext.Msg.alert('Error',
148 'Status:'+action.{@link #response}.status+': '+
149 action.{@link #response}.statusText);
151 if (action.failureType === Ext.form.Action.{@link #SERVER_INVALID}){
152 // server responded with success = false
153 Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
162 fp.getForm().reset();
166 * @property failureType
170 * The XMLHttpRequest object used to perform the action.
175 * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
176 * other, action-specific properties.
182 run : function(options){
187 success : function(response){
192 handleResponse : function(response){
196 // default connection failure
197 failure : function(response){
198 this.response = response;
199 this.failureType = Ext.form.Action.CONNECT_FAILURE;
200 this.form.afterAction(this, false);
204 // shared code among all Actions to validate that there was a response
205 // with either responseText or responseXml
206 processResponse : function(response){
207 this.response = response;
208 if(!response.responseText && !response.responseXML){
211 this.result = this.handleResponse(response);
215 // utility functions used internally
216 getUrl : function(appendParams){
217 var url = this.options.url || this.form.url || this.form.el.dom.action;
219 var p = this.getParams();
221 url = Ext.urlAppend(url, p);
228 getMethod : function(){
229 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
233 getParams : function(){
234 var bp = this.form.baseParams;
235 var p = this.options.params;
237 if(typeof p == "object"){
238 p = Ext.urlEncode(Ext.applyIf(p, bp));
239 }else if(typeof p == 'string' && bp){
240 p += '&' + Ext.urlEncode(bp);
243 p = Ext.urlEncode(bp);
249 createCallback : function(opts){
250 var opts = opts || {};
252 success: this.success,
253 failure: this.failure,
255 timeout: (opts.timeout*1000) || (this.form.timeout*1000),
256 upload: this.form.fileUpload ? this.success : undefined
262 * @class Ext.form.Action.Submit
263 * @extends Ext.form.Action
264 * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s
265 * and processes the returned response.</p>
266 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
267 * {@link Ext.form.BasicForm#submit submit}ting.</p>
268 * <p><u><b>Response Packet Criteria</b></u></p>
269 * <p>A response packet may contain:
270 * <div class="mdetail-params"><ul>
271 * <li><b><code>success</code></b> property : Boolean
272 * <div class="sub-desc">The <code>success</code> property is required.</div></li>
273 * <li><b><code>errors</code></b> property : Object
274 * <div class="sub-desc"><div class="sub-desc">The <code>errors</code> property,
275 * which is optional, contains error messages for invalid fields.</div></li>
277 * <p><u><b>JSON Packets</b></u></p>
278 * <p>By default, response packets are assumed to be JSON, so a typical response
279 * packet may look like this:</p><pre><code>
283 clientCode: "Client not found",
284 portOfLoading: "This field must not be null"
287 * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback
288 * or event handler methods. The object decoded from this JSON is available in the
289 * {@link Ext.form.Action#result result} property.</p>
290 * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>
291 errorReader: new Ext.data.XmlReader({
299 * <p>then the results may be sent back in XML format:</p><pre><code>
300 <?xml version="1.0" encoding="UTF-8"?>
301 <message success="false">
304 <id>clientCode</id>
305 <msg><![CDATA[Code not found. <br /><i>This is a test validation message from the server </i>]]></msg>
308 <id>portOfLoading</id>
309 <msg><![CDATA[Port not found. <br /><i>This is a test validation message from the server </i>]]></msg>
314 * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback
315 * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>
317 Ext.form.Action.Submit = function(form, options){
318 Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
321 Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
323 * @cfg {Ext.data.DataReader} errorReader <p><b>Optional. JSON is interpreted with
324 * no need for an errorReader.</b></p>
325 * <p>A Reader which reads a single record from the returned data. The DataReader's
326 * <b>success</b> property specifies how submission success is determined. The Record's
327 * data provides the error messages to apply to any invalid form Fields.</p>
330 * @cfg {boolean} clientValidation Determines whether a Form's fields are validated
331 * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.
332 * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation
339 var o = this.options,
340 method = this.getMethod(),
341 isGet = method == 'GET';
342 if(o.clientValidation === false || this.form.isValid()){
343 if (o.submitEmptyText === false) {
344 var fields = this.form.items,
346 fields.each(function(f) {
347 if (f.el.getValue() == f.emptyText) {
353 Ext.Ajax.request(Ext.apply(this.createCallback(o), {
354 form:this.form.el.dom,
355 url:this.getUrl(isGet),
358 params:!isGet ? this.getParams() : null,
359 isUpload: this.form.fileUpload
361 if (o.submitEmptyText === false) {
362 Ext.each(emptyFields, function(f) {
363 if (f.applyEmptyText) {
368 }else if (o.clientValidation !== false){ // client validation failed
369 this.failureType = Ext.form.Action.CLIENT_INVALID;
370 this.form.afterAction(this, false);
375 success : function(response){
376 var result = this.processResponse(response);
377 if(result === true || result.success){
378 this.form.afterAction(this, true);
382 this.form.markInvalid(result.errors);
384 this.failureType = Ext.form.Action.SERVER_INVALID;
385 this.form.afterAction(this, false);
389 handleResponse : function(response){
390 if(this.form.errorReader){
391 var rs = this.form.errorReader.read(response);
394 for(var i = 0, len = rs.records.length; i < len; i++) {
395 var r = rs.records[i];
399 if(errors.length < 1){
403 success : rs.success,
407 return Ext.decode(response.responseText);
413 * @class Ext.form.Action.Load
414 * @extends Ext.form.Action
415 * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
416 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
417 * {@link Ext.form.BasicForm#load load}ing.</p>
418 * <p><u><b>Response Packet Criteria</b></u></p>
419 * <p>A response packet <b>must</b> contain:
420 * <div class="mdetail-params"><ul>
421 * <li><b><code>success</code></b> property : Boolean</li>
422 * <li><b><code>data</code></b> property : Object</li>
423 * <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
424 * The individual value object for each Field is passed to the Field's
425 * {@link Ext.form.Field#setValue setValue} method.</div></li>
427 * <p><u><b>JSON Packets</b></u></p>
428 * <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
429 var myFormPanel = new Ext.form.FormPanel({
430 title: 'Client and routing info',
432 fieldLabel: 'Client',
435 fieldLabel: 'Port of loading',
436 name: 'portOfLoading'
438 fieldLabel: 'Port of discharge',
439 name: 'portOfDischarge'
442 myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
443 url: '/getRoutingInfo.php',
445 consignmentRef: myConsignmentRef
447 failure: function(form, action) {
448 Ext.Msg.alert("Load failed", action.result.errorMessage);
452 * a <b>success response</b> packet may look like this:</p><pre><code>
456 clientName: "Fred. Olsen Lines",
457 portOfLoading: "FXT",
458 portOfDischarge: "OSL"
461 * while a <b>failure response</b> packet may look like this:</p><pre><code>
464 errorMessage: "Consignment reference not found"
466 * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s
467 * callback or event handler methods. The object decoded from this JSON is available in the
468 * {@link Ext.form.Action#result result} property.</p>
470 Ext.form.Action.Load = function(form, options){
471 Ext.form.Action.Load.superclass.constructor.call(this, form, options);
472 this.reader = this.form.reader;
475 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
481 Ext.Ajax.request(Ext.apply(
482 this.createCallback(this.options), {
483 method:this.getMethod(),
484 url:this.getUrl(false),
485 headers: this.options.headers,
486 params:this.getParams()
491 success : function(response){
492 var result = this.processResponse(response);
493 if(result === true || !result.success || !result.data){
494 this.failureType = Ext.form.Action.LOAD_FAILURE;
495 this.form.afterAction(this, false);
498 this.form.clearInvalid();
499 this.form.setValues(result.data);
500 this.form.afterAction(this, true);
504 handleResponse : function(response){
505 if(this.form.reader){
506 var rs = this.form.reader.read(response);
507 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
509 success : rs.success,
513 return Ext.decode(response.responseText);
520 * @class Ext.form.Action.DirectLoad
521 * @extends Ext.form.Action.Load
522 * <p>Provides Ext.direct support for loading form data.</p>
523 * <p>This example illustrates usage of Ext.Direct to <b>load</b> a form through Ext.Direct.</p>
525 var myFormPanel = new Ext.form.FormPanel({
526 // configs for FormPanel
527 title: 'Basic Information',
528 renderTo: document.body,
529 width: 300, height: 160,
532 // configs apply to child items
533 defaults: {anchor: '100%'},
534 defaultType: 'textfield',
542 fieldLabel: 'Company',
546 // configs for BasicForm
548 // The server-side method to call for load() requests
549 load: Profile.getBasicInfo,
550 // The server-side must mark the submit handler as a 'formHandler'
551 submit: Profile.updateBasicInfo
553 // specify the order for the passed params
554 paramOrder: ['uid', 'foo']
558 myFormPanel.getForm().load({
559 // pass 2 arguments to server side getBasicInfo method (len=2)
566 * The data packet sent to the server will resemble something like:
570 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
571 "data":[34,"bar"] // note the order of the params
575 * The form will process a data packet returned by the server that is similar
576 * to the following format:
580 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
584 "name":"Fred Flintstone",
585 "company":"Slate Rock and Gravel",
586 "email":"fred.flintstone@slaterg.com"
593 Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
594 constructor: function(form, opts) {
595 Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
600 var args = this.getParams();
601 args.push(this.success, this);
602 this.form.api.load.apply(window, args);
605 getParams : function() {
606 var buf = [], o = {};
607 var bp = this.form.baseParams;
608 var p = this.options.params;
610 var paramOrder = this.form.paramOrder;
612 for(var i = 0, len = paramOrder.length; i < len; i++){
613 buf.push(o[paramOrder[i]]);
615 }else if(this.form.paramsAsHash){
620 // Direct actions have already been processed and therefore
621 // we can directly set the result; Direct Actions do not have
622 // a this.response property.
623 processResponse : function(result) {
624 this.result = result;
628 success : function(response, trans){
629 if(trans.type == Ext.Direct.exceptions.SERVER){
632 Ext.form.Action.DirectLoad.superclass.success.call(this, response);
637 * @class Ext.form.Action.DirectSubmit
638 * @extends Ext.form.Action.Submit
639 * <p>Provides Ext.direct support for submitting form data.</p>
640 * <p>This example illustrates usage of Ext.Direct to <b>submit</b> a form through Ext.Direct.</p>
642 var myFormPanel = new Ext.form.FormPanel({
643 // configs for FormPanel
644 title: 'Basic Information',
645 renderTo: document.body,
646 width: 300, height: 160,
651 myFormPanel.getForm().submit({
660 // configs apply to child items
661 defaults: {anchor: '100%'},
662 defaultType: 'textfield',
670 fieldLabel: 'Company',
674 // configs for BasicForm
676 // The server-side method to call for load() requests
677 load: Profile.getBasicInfo,
678 // The server-side must mark the submit handler as a 'formHandler'
679 submit: Profile.updateBasicInfo
681 // specify the order for the passed params
682 paramOrder: ['uid', 'foo']
685 * The data packet sent to the server will resemble something like:
688 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
692 "extAction":"Profile","extMethod":"updateBasicInfo",
693 "extType":"rpc","extTID":"6","extUpload":"false",
694 "name":"Aaron Conran","email":"aaron@extjs.com","company":"Ext JS, LLC"
699 * The form will process a data packet returned by the server that is similar
702 // sample success packet (batched requests)
705 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
712 // sample failure packet (one request)
714 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
717 "email":"already taken"
724 * Also see the discussion in {@link Ext.form.Action.DirectLoad}.
726 Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
727 constructor : function(form, opts) {
728 Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
730 type : 'directsubmit',
731 // override of Submit
733 var o = this.options;
734 if(o.clientValidation === false || this.form.isValid()){
735 // tag on any additional params to be posted in the
737 this.success.params = this.getParams();
738 this.form.api.submit(this.form.el.dom, this.success, this);
739 }else if (o.clientValidation !== false){ // client validation failed
740 this.failureType = Ext.form.Action.CLIENT_INVALID;
741 this.form.afterAction(this, false);
745 getParams : function() {
747 var bp = this.form.baseParams;
748 var p = this.options.params;
752 // Direct actions have already been processed and therefore
753 // we can directly set the result; Direct Actions do not have
754 // a this.response property.
755 processResponse : function(result) {
756 this.result = result;
760 success : function(response, trans){
761 if(trans.type == Ext.Direct.exceptions.SERVER){
764 Ext.form.Action.DirectSubmit.superclass.success.call(this, response);
768 Ext.form.Action.ACTION_TYPES = {
769 'load' : Ext.form.Action.Load,
770 'submit' : Ext.form.Action.Submit,
771 'directload' : Ext.form.Action.DirectLoad,
772 'directsubmit' : Ext.form.Action.DirectSubmit