Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / src / widgets / form / BasicForm.js
1 /*!
2  * Ext JS Library 3.1.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.BasicForm
9  * @extends Ext.util.Observable
10  * <p>Encapsulates the DOM &lt;form> element at the heart of the {@link Ext.form.FormPanel FormPanel} class, and provides
11  * input field management, validation, submission, and form loading services.</p>
12  * <p>By default, Ext Forms are submitted through Ajax, using an instance of {@link Ext.form.Action.Submit}.
13  * To enable normal browser submission of an Ext Form, use the {@link #standardSubmit} config option.</p>
14  * <p><b><u>File Uploads</u></b></p>
15  * <p>{@link #fileUpload File uploads} are not performed using Ajax submission, that
16  * is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
17  * manner with the DOM <tt>&lt;form></tt> element temporarily modified to have its
18  * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
19  * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
20  * but removed after the return data has been gathered.</p>
21  * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
22  * server is using JSON to send the return object, then the
23  * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
24  * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
25  * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
26  * "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
27  * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
28  * is created containing a <tt>responseText</tt> property in order to conform to the
29  * requirements of event handlers and callbacks.</p>
30  * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
31  * and some server technologies (notably JEE) may require some custom processing in order to
32  * retrieve parameter names and parameter values from the packet content.</p>
33  * @constructor
34  * @param {Mixed} el The form element or its id
35  * @param {Object} config Configuration options
36  */
37 Ext.form.BasicForm = function(el, config){
38     Ext.apply(this, config);
39     if(Ext.isString(this.paramOrder)){
40         this.paramOrder = this.paramOrder.split(/[\s,|]/);
41     }
42     /**
43      * A {@link Ext.util.MixedCollection MixedCollection} containing all the Ext.form.Fields in this form.
44      * @type MixedCollection
45      * @property items
46      */
47     this.items = new Ext.util.MixedCollection(false, function(o){
48         return o.getItemId();
49     });
50     this.addEvents(
51         /**
52          * @event beforeaction
53          * Fires before any action is performed. Return false to cancel the action.
54          * @param {Form} this
55          * @param {Action} action The {@link Ext.form.Action} to be performed
56          */
57         'beforeaction',
58         /**
59          * @event actionfailed
60          * Fires when an action fails.
61          * @param {Form} this
62          * @param {Action} action The {@link Ext.form.Action} that failed
63          */
64         'actionfailed',
65         /**
66          * @event actioncomplete
67          * Fires when an action is completed.
68          * @param {Form} this
69          * @param {Action} action The {@link Ext.form.Action} that completed
70          */
71         'actioncomplete'
72     );
73
74     if(el){
75         this.initEl(el);
76     }
77     Ext.form.BasicForm.superclass.constructor.call(this);
78 };
79
80 Ext.extend(Ext.form.BasicForm, Ext.util.Observable, {
81     /**
82      * @cfg {String} method
83      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
84      */
85     /**
86      * @cfg {DataReader} reader
87      * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read
88      * data when executing 'load' actions. This is optional as there is built-in
89      * support for processing JSON.  For additional information on using an XMLReader
90      * see the example provided in examples/form/xml-form.html.
91      */
92     /**
93      * @cfg {DataReader} errorReader
94      * <p>An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to
95      * read field error messages returned from 'submit' actions. This is optional
96      * as there is built-in support for processing JSON.</p>
97      * <p>The Records which provide messages for the invalid Fields must use the
98      * Field name (or id) as the Record ID, and must contain a field called 'msg'
99      * which contains the error message.</p>
100      * <p>The errorReader does not have to be a full-blown implementation of a
101      * DataReader. It simply needs to implement a <tt>read(xhr)</tt> function
102      * which returns an Array of Records in an object with the following
103      * structure:</p><pre><code>
104 {
105     records: recordArray
106 }
107 </code></pre>
108      */
109     /**
110      * @cfg {String} url
111      * The URL to use for form actions if one isn't supplied in the
112      * <code>{@link #doAction doAction} options</code>.
113      */
114     /**
115      * @cfg {Boolean} fileUpload
116      * Set to true if this form is a file upload.
117      * <p>File uploads are not performed using normal 'Ajax' techniques, that is they are <b>not</b>
118      * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
119      * DOM <tt>&lt;form></tt> element temporarily modified to have its
120      * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
121      * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
122      * but removed after the return data has been gathered.</p>
123      * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
124      * server is using JSON to send the return object, then the
125      * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
126      * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
127      * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
128      * "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
129      * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
130      * is created containing a <tt>responseText</tt> property in order to conform to the
131      * requirements of event handlers and callbacks.</p>
132      * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
133      * and some server technologies (notably JEE) may require some custom processing in order to
134      * retrieve parameter names and parameter values from the packet content.</p>
135      */
136     /**
137      * @cfg {Object} baseParams
138      * <p>Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.</p>
139      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
140      */
141     /**
142      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
143      */
144     timeout: 30,
145
146     /**
147      * @cfg {Object} api (Optional) If specified load and submit actions will be handled
148      * with {@link Ext.form.Action.DirectLoad} and {@link Ext.form.Action.DirectSubmit}.
149      * Methods which have been imported by Ext.Direct can be specified here to load and submit
150      * forms.
151      * Such as the following:<pre><code>
152 api: {
153     load: App.ss.MyProfile.load,
154     submit: App.ss.MyProfile.submit
155 }
156 </code></pre>
157      * <p>Load actions can use <code>{@link #paramOrder}</code> or <code>{@link #paramsAsHash}</code>
158      * to customize how the load method is invoked.
159      * Submit actions will always use a standard form submit. The formHandler configuration must
160      * be set on the associated server-side method which has been imported by Ext.Direct</p>
161      */
162
163     /**
164      * @cfg {Array/String} paramOrder <p>A list of params to be executed server side.
165      * Defaults to <tt>undefined</tt>. Only used for the <code>{@link #api}</code>
166      * <code>load</code> configuration.</p>
167      * <br><p>Specify the params in the order in which they must be executed on the
168      * server-side as either (1) an Array of String values, or (2) a String of params
169      * delimited by either whitespace, comma, or pipe. For example,
170      * any of the following would be acceptable:</p><pre><code>
171 paramOrder: ['param1','param2','param3']
172 paramOrder: 'param1 param2 param3'
173 paramOrder: 'param1,param2,param3'
174 paramOrder: 'param1|param2|param'
175      </code></pre>
176      */
177     paramOrder: undefined,
178
179     /**
180      * @cfg {Boolean} paramsAsHash Only used for the <code>{@link #api}</code>
181      * <code>load</code> configuration. Send parameters as a collection of named
182      * arguments (defaults to <tt>false</tt>). Providing a
183      * <tt>{@link #paramOrder}</tt> nullifies this configuration.
184      */
185     paramsAsHash: false,
186     
187     /**
188      * @cfg {String} waitTitle
189      * The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
190      */
191     waitTitle: 'Please Wait...',
192
193     // private
194     activeAction : null,
195
196     /**
197      * @cfg {Boolean} trackResetOnLoad If set to <tt>true</tt>, {@link #reset}() resets to the last loaded
198      * or {@link #setValues}() data instead of when the form was first created.  Defaults to <tt>false</tt>.
199      */
200     trackResetOnLoad : false,
201
202     /**
203      * @cfg {Boolean} standardSubmit
204      * <p>If set to <tt>true</tt>, standard HTML form submits are used instead
205      * of XHR (Ajax) style form submissions. Defaults to <tt>false</tt>.</p>
206      * <br><p><b>Note:</b> When using <code>standardSubmit</code>, the
207      * <code>options</code> to <code>{@link #submit}</code> are ignored because
208      * Ext's Ajax infrastracture is bypassed. To pass extra parameters (e.g.
209      * <code>baseParams</code> and <code>params</code>), utilize hidden fields
210      * to submit extra data, for example:</p>
211      * <pre><code>
212 new Ext.FormPanel({
213     standardSubmit: true,
214     baseParams: {
215         foo: 'bar'
216     },
217     {@link url}: 'myProcess.php',
218     items: [{
219         xtype: 'textfield',
220         name: 'userName'
221     }],
222     buttons: [{
223         text: 'Save',
224         handler: function(){
225             var fp = this.ownerCt.ownerCt,
226                 form = fp.getForm();
227             if (form.isValid()) {
228                 // check if there are baseParams and if
229                 // hiddent items have been added already
230                 if (fp.baseParams && !fp.paramsAdded) {
231                     // add hidden items for all baseParams
232                     for (i in fp.baseParams) {
233                         fp.add({
234                             xtype: 'hidden',
235                             name: i,
236                             value: fp.baseParams[i]
237                         });
238                     }
239                     fp.doLayout();
240                     // set a custom flag to prevent re-adding
241                     fp.paramsAdded = true;
242                 }
243                 form.{@link #submit}();
244             }
245         }
246     }]
247 });
248      * </code></pre>
249      */
250     /**
251      * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
252      * element by passing it or its id or mask the form itself by passing in true.
253      * @type Mixed
254      * @property waitMsgTarget
255      */
256
257     // private
258     initEl : function(el){
259         this.el = Ext.get(el);
260         this.id = this.el.id || Ext.id();
261         if(!this.standardSubmit){
262             this.el.on('submit', this.onSubmit, this);
263         }
264         this.el.addClass('x-form');
265     },
266
267     /**
268      * Get the HTML form Element
269      * @return Ext.Element
270      */
271     getEl: function(){
272         return this.el;
273     },
274
275     // private
276     onSubmit : function(e){
277         e.stopEvent();
278     },
279
280     // private
281     destroy: function() {
282         this.items.each(function(f){
283             Ext.destroy(f);
284         });
285         if(this.el){
286             this.el.removeAllListeners();
287             this.el.remove();
288         }
289         this.purgeListeners();
290     },
291
292     /**
293      * Returns true if client-side validation on the form is successful.
294      * @return Boolean
295      */
296     isValid : function(){
297         var valid = true;
298         this.items.each(function(f){
299            if(!f.validate()){
300                valid = false;
301            }
302         });
303         return valid;
304     },
305
306     /**
307      * <p>Returns true if any fields in this form have changed from their original values.</p>
308      * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
309      * Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
310      * or {@link #loadRecord}.</p>
311      * @return Boolean
312      */
313     isDirty : function(){
314         var dirty = false;
315         this.items.each(function(f){
316            if(f.isDirty()){
317                dirty = true;
318                return false;
319            }
320         });
321         return dirty;
322     },
323
324     /**
325      * Performs a predefined action ({@link Ext.form.Action.Submit} or
326      * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
327      * to perform application-specific processing.
328      * @param {String/Object} actionName The name of the predefined action type,
329      * or instance of {@link Ext.form.Action} to perform.
330      * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
331      * All of the config options listed below are supported by both the
332      * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
333      * actions unless otherwise noted (custom actions could also accept
334      * other config options):<ul>
335      *
336      * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
337      * to the form's {@link #url}.)</div></li>
338      *
339      * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
340      * to the form's method, or POST if not defined)</div></li>
341      *
342      * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
343      * (defaults to the form's baseParams, or none if not defined)</p>
344      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
345      *
346      * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
347      * (defaults to the form's default headers)</div></li>
348      *
349      * <li><b>success</b> : Function<div class="sub-desc">The callback that will
350      * be invoked after a successful response (see top of
351      * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
352      * for a description of what constitutes a successful response).
353      * The function is passed the following parameters:<ul>
354      * <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
355      * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
356      * <div class="sub-desc">The action object contains these properties of interest:<ul>
357      * <li><tt>{@link Ext.form.Action#response response}</tt></li>
358      * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
359      * <li><tt>{@link Ext.form.Action#type type}</tt></li>
360      * </ul></div></li></ul></div></li>
361      *
362      * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
363      * failed transaction attempt. The function is passed the following parameters:<ul>
364      * <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
365      * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
366      * <div class="sub-desc">The action object contains these properties of interest:<ul>
367      * <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
368      * <li><tt>{@link Ext.form.Action#response response}</tt></li>
369      * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
370      * <li><tt>{@link Ext.form.Action#type type}</tt></li>
371      * </ul></div></li></ul></div></li>
372      *
373      * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
374      * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
375      *
376      * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
377      * Determines whether a Form's fields are validated in a final call to
378      * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
379      * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
380      *
381      * @return {BasicForm} this
382      */
383     doAction : function(action, options){
384         if(Ext.isString(action)){
385             action = new Ext.form.Action.ACTION_TYPES[action](this, options);
386         }
387         if(this.fireEvent('beforeaction', this, action) !== false){
388             this.beforeAction(action);
389             action.run.defer(100, action);
390         }
391         return this;
392     },
393
394     /**
395      * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
396      * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
397      * <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
398      * <p>The following code:</p><pre><code>
399 myFormPanel.getForm().submit({
400     clientValidation: true,
401     url: 'updateConsignment.php',
402     params: {
403         newStatus: 'delivered'
404     },
405     success: function(form, action) {
406        Ext.Msg.alert('Success', action.result.msg);
407     },
408     failure: function(form, action) {
409         switch (action.failureType) {
410             case Ext.form.Action.CLIENT_INVALID:
411                 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
412                 break;
413             case Ext.form.Action.CONNECT_FAILURE:
414                 Ext.Msg.alert('Failure', 'Ajax communication failed');
415                 break;
416             case Ext.form.Action.SERVER_INVALID:
417                Ext.Msg.alert('Failure', action.result.msg);
418        }
419     }
420 });
421 </code></pre>
422      * would process the following server response for a successful submission:<pre><code>
423 {
424     "success":true, // note this is Boolean, not string
425     "msg":"Consignment updated"
426 }
427 </code></pre>
428      * and the following server response for a failed submission:<pre><code>
429 {
430     "success":false, // note this is Boolean, not string
431     "msg":"You do not have permission to perform this operation"
432 }
433 </code></pre>
434      * @return {BasicForm} this
435      */
436     submit : function(options){
437         if(this.standardSubmit){
438             var v = this.isValid();
439             if(v){
440                 var el = this.el.dom;
441                 if(this.url && Ext.isEmpty(el.action)){
442                     el.action = this.url;
443                 }
444                 el.submit();
445             }
446             return v;
447         }
448         var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
449         this.doAction(submitAction, options);
450         return this;
451     },
452
453     /**
454      * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
455      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
456      * @return {BasicForm} this
457      */
458     load : function(options){
459         var loadAction = String.format('{0}load', this.api ? 'direct' : '');
460         this.doAction(loadAction, options);
461         return this;
462     },
463
464     /**
465      * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
466      * @param {Record} record The record to edit
467      * @return {BasicForm} this
468      */
469     updateRecord : function(record){
470         record.beginEdit();
471         var fs = record.fields;
472         fs.each(function(f){
473             var field = this.findField(f.name);
474             if(field){
475                 record.set(f.name, field.getValue());
476             }
477         }, this);
478         record.endEdit();
479         return this;
480     },
481
482     /**
483      * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
484      * {@link Ext.data.Record#data record data}.
485      * See also {@link #trackResetOnLoad}.
486      * @param {Record} record The record to load
487      * @return {BasicForm} this
488      */
489     loadRecord : function(record){
490         this.setValues(record.data);
491         return this;
492     },
493
494     // private
495     beforeAction : function(action){
496         var o = action.options;
497         if(o.waitMsg){
498             if(this.waitMsgTarget === true){
499                 this.el.mask(o.waitMsg, 'x-mask-loading');
500             }else if(this.waitMsgTarget){
501                 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
502                 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
503             }else{
504                 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
505             }
506         }
507     },
508
509     // private
510     afterAction : function(action, success){
511         this.activeAction = null;
512         var o = action.options;
513         if(o.waitMsg){
514             if(this.waitMsgTarget === true){
515                 this.el.unmask();
516             }else if(this.waitMsgTarget){
517                 this.waitMsgTarget.unmask();
518             }else{
519                 Ext.MessageBox.updateProgress(1);
520                 Ext.MessageBox.hide();
521             }
522         }
523         if(success){
524             if(o.reset){
525                 this.reset();
526             }
527             Ext.callback(o.success, o.scope, [this, action]);
528             this.fireEvent('actioncomplete', this, action);
529         }else{
530             Ext.callback(o.failure, o.scope, [this, action]);
531             this.fireEvent('actionfailed', this, action);
532         }
533     },
534
535     /**
536      * Find a {@link Ext.form.Field} in this form.
537      * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
538      * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
539      * @return Field
540      */
541     findField : function(id){
542         var field = this.items.get(id);
543         if(!Ext.isObject(field)){
544             this.items.each(function(f){
545                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
546                     field = f;
547                     return false;
548                 }
549             });
550         }
551         return field || null;
552     },
553
554
555     /**
556      * Mark fields in this form invalid in bulk.
557      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
558      * @return {BasicForm} this
559      */
560     markInvalid : function(errors){
561         if(Ext.isArray(errors)){
562             for(var i = 0, len = errors.length; i < len; i++){
563                 var fieldError = errors[i];
564                 var f = this.findField(fieldError.id);
565                 if(f){
566                     f.markInvalid(fieldError.msg);
567                 }
568             }
569         }else{
570             var field, id;
571             for(id in errors){
572                 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
573                     field.markInvalid(errors[id]);
574                 }
575             }
576         }
577         return this;
578     },
579
580     /**
581      * Set values for fields in this form in bulk.
582      * @param {Array/Object} values Either an array in the form:<pre><code>
583 [{id:'clientName', value:'Fred. Olsen Lines'},
584  {id:'portOfLoading', value:'FXT'},
585  {id:'portOfDischarge', value:'OSL'} ]</code></pre>
586      * or an object hash of the form:<pre><code>
587 {
588     clientName: 'Fred. Olsen Lines',
589     portOfLoading: 'FXT',
590     portOfDischarge: 'OSL'
591 }</code></pre>
592      * @return {BasicForm} this
593      */
594     setValues : function(values){
595         if(Ext.isArray(values)){ // array of objects
596             for(var i = 0, len = values.length; i < len; i++){
597                 var v = values[i];
598                 var f = this.findField(v.id);
599                 if(f){
600                     f.setValue(v.value);
601                     if(this.trackResetOnLoad){
602                         f.originalValue = f.getValue();
603                     }
604                 }
605             }
606         }else{ // object hash
607             var field, id;
608             for(id in values){
609                 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
610                     field.setValue(values[id]);
611                     if(this.trackResetOnLoad){
612                         field.originalValue = field.getValue();
613                     }
614                 }
615             }
616         }
617         return this;
618     },
619
620     /**
621      * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
622      * If multiple fields exist with the same name they are returned as an array.</p>
623      * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
624      * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
625      * value can potentially be the emptyText of a field.</p>
626      * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
627      * @return {String/Object}
628      */
629     getValues : function(asString){
630         var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
631         if(asString === true){
632             return fs;
633         }
634         return Ext.urlDecode(fs);
635     },
636
637     /**
638      * Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
639      * If multiple fields exist with the same name they are returned as an array.
640      * @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
641      * @return {Object} The values in the form
642      */
643     getFieldValues : function(dirtyOnly){
644         var o = {},
645             n,
646             key,
647             val;
648         this.items.each(function(f){
649             if(dirtyOnly !== true || f.isDirty()){
650                 n = f.getName();
651                 key = o[n];
652                 val = f.getValue();
653                 
654                 if(Ext.isDefined(key)){
655                     if(Ext.isArray(key)){
656                         o[n].push(val);
657                     }else{
658                         o[n] = [key, val];
659                     }
660                 }else{
661                     o[n] = val;
662                 }
663             }
664         });
665         return o;
666     },
667
668     /**
669      * Clears all invalid messages in this form.
670      * @return {BasicForm} this
671      */
672     clearInvalid : function(){
673         this.items.each(function(f){
674            f.clearInvalid();
675         });
676         return this;
677     },
678
679     /**
680      * Resets this form.
681      * @return {BasicForm} this
682      */
683     reset : function(){
684         this.items.each(function(f){
685             f.reset();
686         });
687         return this;
688     },
689
690     /**
691      * Add Ext.form Components to this form's Collection. This does not result in rendering of
692      * the passed Component, it just enables the form to validate Fields, and distribute values to
693      * Fields.
694      * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
695      * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
696      * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
697      * collection.</b></p>
698      * @param {Field} field1
699      * @param {Field} field2 (optional)
700      * @param {Field} etc (optional)
701      * @return {BasicForm} this
702      */
703     add : function(){
704         this.items.addAll(Array.prototype.slice.call(arguments, 0));
705         return this;
706     },
707
708
709     /**
710      * Removes a field from the items collection (does NOT remove its markup).
711      * @param {Field} field
712      * @return {BasicForm} this
713      */
714     remove : function(field){
715         this.items.remove(field);
716         return this;
717     },
718
719     /**
720      * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
721      * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
722      * @return {BasicForm} this
723      */
724     render : function(){
725         this.items.each(function(f){
726             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
727                 f.applyToMarkup(f.id);
728             }
729         });
730         return this;
731     },
732
733     /**
734      * Calls {@link Ext#apply} for all fields in this form with the passed object.
735      * @param {Object} values
736      * @return {BasicForm} this
737      */
738     applyToFields : function(o){
739         this.items.each(function(f){
740            Ext.apply(f, o);
741         });
742         return this;
743     },
744
745     /**
746      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
747      * @param {Object} values
748      * @return {BasicForm} this
749      */
750     applyIfToFields : function(o){
751         this.items.each(function(f){
752            Ext.applyIf(f, o);
753         });
754         return this;
755     },
756
757     callFieldMethod : function(fnName, args){
758         args = args || [];
759         this.items.each(function(f){
760             if(Ext.isFunction(f[fnName])){
761                 f[fnName].apply(f, args);
762             }
763         });
764         return this;
765     }
766 });
767
768 // back compat
769 Ext.BasicForm = Ext.form.BasicForm;