3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.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 setupEmptyFields = function(f){
347 if (f.el.getValue() == f.emptyText) {
351 if(f.isComposite && f.rendered){
352 f.items.each(setupEmptyFields);
356 fields.each(setupEmptyFields);
358 Ext.Ajax.request(Ext.apply(this.createCallback(o), {
359 form:this.form.el.dom,
360 url:this.getUrl(isGet),
363 params:!isGet ? this.getParams() : null,
364 isUpload: this.form.fileUpload
366 if (o.submitEmptyText === false) {
367 Ext.each(emptyFields, function(f) {
368 if (f.applyEmptyText) {
373 }else if (o.clientValidation !== false){ // client validation failed
374 this.failureType = Ext.form.Action.CLIENT_INVALID;
375 this.form.afterAction(this, false);
380 success : function(response){
381 var result = this.processResponse(response);
382 if(result === true || result.success){
383 this.form.afterAction(this, true);
387 this.form.markInvalid(result.errors);
389 this.failureType = Ext.form.Action.SERVER_INVALID;
390 this.form.afterAction(this, false);
394 handleResponse : function(response){
395 if(this.form.errorReader){
396 var rs = this.form.errorReader.read(response);
399 for(var i = 0, len = rs.records.length; i < len; i++) {
400 var r = rs.records[i];
404 if(errors.length < 1){
408 success : rs.success,
412 return Ext.decode(response.responseText);
418 * @class Ext.form.Action.Load
419 * @extends Ext.form.Action
420 * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
421 * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
422 * {@link Ext.form.BasicForm#load load}ing.</p>
423 * <p><u><b>Response Packet Criteria</b></u></p>
424 * <p>A response packet <b>must</b> contain:
425 * <div class="mdetail-params"><ul>
426 * <li><b><code>success</code></b> property : Boolean</li>
427 * <li><b><code>data</code></b> property : Object</li>
428 * <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
429 * The individual value object for each Field is passed to the Field's
430 * {@link Ext.form.Field#setValue setValue} method.</div></li>
432 * <p><u><b>JSON Packets</b></u></p>
433 * <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
434 var myFormPanel = new Ext.form.FormPanel({
435 title: 'Client and routing info',
437 fieldLabel: 'Client',
440 fieldLabel: 'Port of loading',
441 name: 'portOfLoading'
443 fieldLabel: 'Port of discharge',
444 name: 'portOfDischarge'
447 myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
448 url: '/getRoutingInfo.php',
450 consignmentRef: myConsignmentRef
452 failure: function(form, action) {
453 Ext.Msg.alert("Load failed", action.result.errorMessage);
457 * a <b>success response</b> packet may look like this:</p><pre><code>
461 clientName: "Fred. Olsen Lines",
462 portOfLoading: "FXT",
463 portOfDischarge: "OSL"
466 * while a <b>failure response</b> packet may look like this:</p><pre><code>
469 errorMessage: "Consignment reference not found"
471 * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s
472 * callback or event handler methods. The object decoded from this JSON is available in the
473 * {@link Ext.form.Action#result result} property.</p>
475 Ext.form.Action.Load = function(form, options){
476 Ext.form.Action.Load.superclass.constructor.call(this, form, options);
477 this.reader = this.form.reader;
480 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
486 Ext.Ajax.request(Ext.apply(
487 this.createCallback(this.options), {
488 method:this.getMethod(),
489 url:this.getUrl(false),
490 headers: this.options.headers,
491 params:this.getParams()
496 success : function(response){
497 var result = this.processResponse(response);
498 if(result === true || !result.success || !result.data){
499 this.failureType = Ext.form.Action.LOAD_FAILURE;
500 this.form.afterAction(this, false);
503 this.form.clearInvalid();
504 this.form.setValues(result.data);
505 this.form.afterAction(this, true);
509 handleResponse : function(response){
510 if(this.form.reader){
511 var rs = this.form.reader.read(response);
512 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
514 success : rs.success,
518 return Ext.decode(response.responseText);
525 * @class Ext.form.Action.DirectLoad
526 * @extends Ext.form.Action.Load
527 * <p>Provides Ext.direct support for loading form data.</p>
528 * <p>This example illustrates usage of Ext.Direct to <b>load</b> a form through Ext.Direct.</p>
530 var myFormPanel = new Ext.form.FormPanel({
531 // configs for FormPanel
532 title: 'Basic Information',
533 renderTo: document.body,
534 width: 300, height: 160,
537 // configs apply to child items
538 defaults: {anchor: '100%'},
539 defaultType: 'textfield',
547 fieldLabel: 'Company',
551 // configs for BasicForm
553 // The server-side method to call for load() requests
554 load: Profile.getBasicInfo,
555 // The server-side must mark the submit handler as a 'formHandler'
556 submit: Profile.updateBasicInfo
558 // specify the order for the passed params
559 paramOrder: ['uid', 'foo']
563 myFormPanel.getForm().load({
564 // pass 2 arguments to server side getBasicInfo method (len=2)
571 * The data packet sent to the server will resemble something like:
575 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
576 "data":[34,"bar"] // note the order of the params
580 * The form will process a data packet returned by the server that is similar
581 * to the following format:
585 "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
589 "name":"Fred Flintstone",
590 "company":"Slate Rock and Gravel",
591 "email":"fred.flintstone@slaterg.com"
598 Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
599 constructor: function(form, opts) {
600 Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
605 var args = this.getParams();
606 args.push(this.success, this);
607 this.form.api.load.apply(window, args);
610 getParams : function() {
611 var buf = [], o = {};
612 var bp = this.form.baseParams;
613 var p = this.options.params;
615 var paramOrder = this.form.paramOrder;
617 for(var i = 0, len = paramOrder.length; i < len; i++){
618 buf.push(o[paramOrder[i]]);
620 }else if(this.form.paramsAsHash){
625 // Direct actions have already been processed and therefore
626 // we can directly set the result; Direct Actions do not have
627 // a this.response property.
628 processResponse : function(result) {
629 this.result = result;
633 success : function(response, trans){
634 if(trans.type == Ext.Direct.exceptions.SERVER){
637 Ext.form.Action.DirectLoad.superclass.success.call(this, response);
642 * @class Ext.form.Action.DirectSubmit
643 * @extends Ext.form.Action.Submit
644 * <p>Provides Ext.direct support for submitting form data.</p>
645 * <p>This example illustrates usage of Ext.Direct to <b>submit</b> a form through Ext.Direct.</p>
647 var myFormPanel = new Ext.form.FormPanel({
648 // configs for FormPanel
649 title: 'Basic Information',
650 renderTo: document.body,
651 width: 300, height: 160,
656 myFormPanel.getForm().submit({
665 // configs apply to child items
666 defaults: {anchor: '100%'},
667 defaultType: 'textfield',
675 fieldLabel: 'Company',
679 // configs for BasicForm
681 // The server-side method to call for load() requests
682 load: Profile.getBasicInfo,
683 // The server-side must mark the submit handler as a 'formHandler'
684 submit: Profile.updateBasicInfo
686 // specify the order for the passed params
687 paramOrder: ['uid', 'foo']
690 * The data packet sent to the server will resemble something like:
693 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
697 "extAction":"Profile","extMethod":"updateBasicInfo",
698 "extType":"rpc","extTID":"6","extUpload":"false",
699 "name":"Aaron Conran","email":"aaron@extjs.com","company":"Ext JS, LLC"
704 * The form will process a data packet returned by the server that is similar
707 // sample success packet (batched requests)
710 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
717 // sample failure packet (one request)
719 "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
722 "email":"already taken"
729 * Also see the discussion in {@link Ext.form.Action.DirectLoad}.
731 Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
732 constructor : function(form, opts) {
733 Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
735 type : 'directsubmit',
736 // override of Submit
738 var o = this.options;
739 if(o.clientValidation === false || this.form.isValid()){
740 // tag on any additional params to be posted in the
742 this.success.params = this.getParams();
743 this.form.api.submit(this.form.el.dom, this.success, this);
744 }else if (o.clientValidation !== false){ // client validation failed
745 this.failureType = Ext.form.Action.CLIENT_INVALID;
746 this.form.afterAction(this, false);
750 getParams : function() {
752 var bp = this.form.baseParams;
753 var p = this.options.params;
757 // Direct actions have already been processed and therefore
758 // we can directly set the result; Direct Actions do not have
759 // a this.response property.
760 processResponse : function(result) {
761 this.result = result;
765 success : function(response, trans){
766 if(trans.type == Ext.Direct.exceptions.SERVER){
769 Ext.form.Action.DirectSubmit.superclass.success.call(this, response);
773 Ext.form.Action.ACTION_TYPES = {
774 'load' : Ext.form.Action.Load,
775 'submit' : Ext.form.Action.Submit,
776 'directload' : Ext.form.Action.DirectLoad,
777 'directsubmit' : Ext.form.Action.DirectSubmit