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