Upgrade to ExtJS 3.2.0 - Released 03/30/2010
[extjs.git] / src / widgets / form / BasicForm.js
1 /*!
2  * Ext JS Library 3.2.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
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     /**
282      * Destroys this object.
283      * @private
284      * @param {Boolean} bound true if the object is bound to a form panel. If this is the case
285      * the FormPanel will take care of destroying certain things, so we're just doubling up.
286      */
287     destroy: function(bound){
288         if(bound !== true){
289             this.items.each(function(f){
290                 Ext.destroy(f);
291             });
292             Ext.destroy(this.el);
293         }
294         this.items.clear();
295         this.purgeListeners();
296     },
297
298     /**
299      * Returns true if client-side validation on the form is successful.
300      * @return Boolean
301      */
302     isValid : function(){
303         var valid = true;
304         this.items.each(function(f){
305            if(!f.validate()){
306                valid = false;
307            }
308         });
309         return valid;
310     },
311
312     /**
313      * <p>Returns true if any fields in this form have changed from their original values.</p>
314      * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
315      * Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
316      * or {@link #loadRecord}.</p>
317      * @return Boolean
318      */
319     isDirty : function(){
320         var dirty = false;
321         this.items.each(function(f){
322            if(f.isDirty()){
323                dirty = true;
324                return false;
325            }
326         });
327         return dirty;
328     },
329
330     /**
331      * Performs a predefined action ({@link Ext.form.Action.Submit} or
332      * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
333      * to perform application-specific processing.
334      * @param {String/Object} actionName The name of the predefined action type,
335      * or instance of {@link Ext.form.Action} to perform.
336      * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
337      * All of the config options listed below are supported by both the
338      * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
339      * actions unless otherwise noted (custom actions could also accept
340      * other config options):<ul>
341      *
342      * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
343      * to the form's {@link #url}.)</div></li>
344      *
345      * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
346      * to the form's method, or POST if not defined)</div></li>
347      *
348      * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
349      * (defaults to the form's baseParams, or none if not defined)</p>
350      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
351      *
352      * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
353      * (defaults to the form's default headers)</div></li>
354      *
355      * <li><b>success</b> : Function<div class="sub-desc">The callback that will
356      * be invoked after a successful response (see top of
357      * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
358      * for a description of what constitutes a successful response).
359      * The function is passed the following parameters:<ul>
360      * <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
361      * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
362      * <div class="sub-desc">The action object contains these properties of interest:<ul>
363      * <li><tt>{@link Ext.form.Action#response response}</tt></li>
364      * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
365      * <li><tt>{@link Ext.form.Action#type type}</tt></li>
366      * </ul></div></li></ul></div></li>
367      *
368      * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
369      * failed transaction attempt. The function is passed the following parameters:<ul>
370      * <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
371      * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
372      * <div class="sub-desc">The action object contains these properties of interest:<ul>
373      * <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
374      * <li><tt>{@link Ext.form.Action#response response}</tt></li>
375      * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
376      * <li><tt>{@link Ext.form.Action#type type}</tt></li>
377      * </ul></div></li></ul></div></li>
378      *
379      * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
380      * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
381      *
382      * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
383      * Determines whether a Form's fields are validated in a final call to
384      * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
385      * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
386      *
387      * @return {BasicForm} this
388      */
389     doAction : function(action, options){
390         if(Ext.isString(action)){
391             action = new Ext.form.Action.ACTION_TYPES[action](this, options);
392         }
393         if(this.fireEvent('beforeaction', this, action) !== false){
394             this.beforeAction(action);
395             action.run.defer(100, action);
396         }
397         return this;
398     },
399
400     /**
401      * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
402      * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
403      * <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
404      * <p>The following code:</p><pre><code>
405 myFormPanel.getForm().submit({
406     clientValidation: true,
407     url: 'updateConsignment.php',
408     params: {
409         newStatus: 'delivered'
410     },
411     success: function(form, action) {
412        Ext.Msg.alert('Success', action.result.msg);
413     },
414     failure: function(form, action) {
415         switch (action.failureType) {
416             case Ext.form.Action.CLIENT_INVALID:
417                 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
418                 break;
419             case Ext.form.Action.CONNECT_FAILURE:
420                 Ext.Msg.alert('Failure', 'Ajax communication failed');
421                 break;
422             case Ext.form.Action.SERVER_INVALID:
423                Ext.Msg.alert('Failure', action.result.msg);
424        }
425     }
426 });
427 </code></pre>
428      * would process the following server response for a successful submission:<pre><code>
429 {
430     "success":true, // note this is Boolean, not string
431     "msg":"Consignment updated"
432 }
433 </code></pre>
434      * and the following server response for a failed submission:<pre><code>
435 {
436     "success":false, // note this is Boolean, not string
437     "msg":"You do not have permission to perform this operation"
438 }
439 </code></pre>
440      * @return {BasicForm} this
441      */
442     submit : function(options){
443         options = options || {};
444         if(this.standardSubmit){
445             var v = options.clientValidation === false || this.isValid();
446             if(v){
447                 var el = this.el.dom;
448                 if(this.url && Ext.isEmpty(el.action)){
449                     el.action = this.url;
450                 }
451                 el.submit();
452             }
453             return v;
454         }
455         var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
456         this.doAction(submitAction, options);
457         return this;
458     },
459
460     /**
461      * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
462      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
463      * @return {BasicForm} this
464      */
465     load : function(options){
466         var loadAction = String.format('{0}load', this.api ? 'direct' : '');
467         this.doAction(loadAction, options);
468         return this;
469     },
470
471     /**
472      * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
473      * @param {Record} record The record to edit
474      * @return {BasicForm} this
475      */
476     updateRecord : function(record){
477         record.beginEdit();
478         var fs = record.fields;
479         fs.each(function(f){
480             var field = this.findField(f.name);
481             if(field){
482                 record.set(f.name, field.getValue());
483             }
484         }, this);
485         record.endEdit();
486         return this;
487     },
488
489     /**
490      * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
491      * {@link Ext.data.Record#data record data}.
492      * See also {@link #trackResetOnLoad}.
493      * @param {Record} record The record to load
494      * @return {BasicForm} this
495      */
496     loadRecord : function(record){
497         this.setValues(record.data);
498         return this;
499     },
500
501     // private
502     beforeAction : function(action){
503         // Call HtmlEditor's syncValue before actions
504         this.items.each(function(f){
505             if(f.isFormField && f.syncValue){
506                 f.syncValue();
507             }
508         });
509         var o = action.options;
510         if(o.waitMsg){
511             if(this.waitMsgTarget === true){
512                 this.el.mask(o.waitMsg, 'x-mask-loading');
513             }else if(this.waitMsgTarget){
514                 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
515                 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
516             }else{
517                 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
518             }
519         }
520     },
521
522     // private
523     afterAction : function(action, success){
524         this.activeAction = null;
525         var o = action.options;
526         if(o.waitMsg){
527             if(this.waitMsgTarget === true){
528                 this.el.unmask();
529             }else if(this.waitMsgTarget){
530                 this.waitMsgTarget.unmask();
531             }else{
532                 Ext.MessageBox.updateProgress(1);
533                 Ext.MessageBox.hide();
534             }
535         }
536         if(success){
537             if(o.reset){
538                 this.reset();
539             }
540             Ext.callback(o.success, o.scope, [this, action]);
541             this.fireEvent('actioncomplete', this, action);
542         }else{
543             Ext.callback(o.failure, o.scope, [this, action]);
544             this.fireEvent('actionfailed', this, action);
545         }
546     },
547
548     /**
549      * Find a {@link Ext.form.Field} in this form.
550      * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
551      * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
552      * @return Field
553      */
554     findField : function(id) {
555         var field = this.items.get(id);
556
557         if (!Ext.isObject(field)) {
558             //searches for the field corresponding to the given id. Used recursively for composite fields
559             var findMatchingField = function(f) {
560                 if (f.isFormField) {
561                     if (f.dataIndex == id || f.id == id || f.getName() == id) {
562                         field = f;
563                         return false;
564                     } else if (f.isComposite) {
565                         return f.items.each(findMatchingField);
566                     }
567                 }
568             };
569
570             this.items.each(findMatchingField);
571         }
572         return field || null;
573     },
574
575
576     /**
577      * Mark fields in this form invalid in bulk.
578      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
579      * @return {BasicForm} this
580      */
581     markInvalid : function(errors){
582         if (Ext.isArray(errors)) {
583             for(var i = 0, len = errors.length; i < len; i++){
584                 var fieldError = errors[i];
585                 var f = this.findField(fieldError.id);
586                 if(f){
587                     f.markInvalid(fieldError.msg);
588                 }
589             }
590         } else {
591             var field, id;
592             for(id in errors){
593                 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
594                     field.markInvalid(errors[id]);
595                 }
596             }
597         }
598
599         return this;
600     },
601
602     /**
603      * Set values for fields in this form in bulk.
604      * @param {Array/Object} values Either an array in the form:<pre><code>
605 [{id:'clientName', value:'Fred. Olsen Lines'},
606  {id:'portOfLoading', value:'FXT'},
607  {id:'portOfDischarge', value:'OSL'} ]</code></pre>
608      * or an object hash of the form:<pre><code>
609 {
610     clientName: 'Fred. Olsen Lines',
611     portOfLoading: 'FXT',
612     portOfDischarge: 'OSL'
613 }</code></pre>
614      * @return {BasicForm} this
615      */
616     setValues : function(values){
617         if(Ext.isArray(values)){ // array of objects
618             for(var i = 0, len = values.length; i < len; i++){
619                 var v = values[i];
620                 var f = this.findField(v.id);
621                 if(f){
622                     f.setValue(v.value);
623                     if(this.trackResetOnLoad){
624                         f.originalValue = f.getValue();
625                     }
626                 }
627             }
628         }else{ // object hash
629             var field, id;
630             for(id in values){
631                 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
632                     field.setValue(values[id]);
633                     if(this.trackResetOnLoad){
634                         field.originalValue = field.getValue();
635                     }
636                 }
637             }
638         }
639         return this;
640     },
641
642     /**
643      * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
644      * If multiple fields exist with the same name they are returned as an array.</p>
645      * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
646      * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
647      * value can potentially be the emptyText of a field.</p>
648      * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
649      * @return {String/Object}
650      */
651     getValues : function(asString){
652         var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
653         if(asString === true){
654             return fs;
655         }
656         return Ext.urlDecode(fs);
657     },
658
659     /**
660      * Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
661      * If multiple fields exist with the same name they are returned as an array.
662      * @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
663      * @return {Object} The values in the form
664      */
665     getFieldValues : function(dirtyOnly){
666         var o = {},
667             n,
668             key,
669             val;
670         this.items.each(function(f) {
671             if (dirtyOnly !== true || f.isDirty()) {
672                 n = f.getName();
673                 key = o[n];
674                 val = f.getValue();
675
676                 if(Ext.isDefined(key)){
677                     if(Ext.isArray(key)){
678                         o[n].push(val);
679                     }else{
680                         o[n] = [key, val];
681                     }
682                 }else{
683                     o[n] = val;
684                 }
685             }
686         });
687         return o;
688     },
689
690     /**
691      * Clears all invalid messages in this form.
692      * @return {BasicForm} this
693      */
694     clearInvalid : function(){
695         this.items.each(function(f){
696            f.clearInvalid();
697         });
698         return this;
699     },
700
701     /**
702      * Resets this form.
703      * @return {BasicForm} this
704      */
705     reset : function(){
706         this.items.each(function(f){
707             f.reset();
708         });
709         return this;
710     },
711
712     /**
713      * Add Ext.form Components to this form's Collection. This does not result in rendering of
714      * the passed Component, it just enables the form to validate Fields, and distribute values to
715      * Fields.
716      * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
717      * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
718      * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
719      * collection.</b></p>
720      * @param {Field} field1
721      * @param {Field} field2 (optional)
722      * @param {Field} etc (optional)
723      * @return {BasicForm} this
724      */
725     add : function(){
726         this.items.addAll(Array.prototype.slice.call(arguments, 0));
727         return this;
728     },
729
730     /**
731      * Removes a field from the items collection (does NOT remove its markup).
732      * @param {Field} field
733      * @return {BasicForm} this
734      */
735     remove : function(field){
736         this.items.remove(field);
737         return this;
738     },
739
740     /**
741      * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
742      * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
743      * @return {BasicForm} this
744      */
745     render : function(){
746         this.items.each(function(f){
747             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
748                 f.applyToMarkup(f.id);
749             }
750         });
751         return this;
752     },
753
754     /**
755      * Calls {@link Ext#apply} for all fields in this form with the passed object.
756      * @param {Object} values
757      * @return {BasicForm} this
758      */
759     applyToFields : function(o){
760         this.items.each(function(f){
761            Ext.apply(f, o);
762         });
763         return this;
764     },
765
766     /**
767      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
768      * @param {Object} values
769      * @return {BasicForm} this
770      */
771     applyIfToFields : function(o){
772         this.items.each(function(f){
773            Ext.applyIf(f, o);
774         });
775         return this;
776     },
777
778     callFieldMethod : function(fnName, args){
779         args = args || [];
780         this.items.each(function(f){
781             if(Ext.isFunction(f[fnName])){
782                 f[fnName].apply(f, args);
783             }
784         });
785         return this;
786     }
787 });
788
789 // back compat
790 Ext.BasicForm = Ext.form.BasicForm;