Upgrade to ExtJS 3.3.1 - Released 11/30/2010
[extjs.git] / src / widgets / form / BasicForm.js
1 /*!
2  * Ext JS Library 3.3.1
3  * Copyright(c) 2006-2010 Sencha Inc.
4  * licensing@sencha.com
5  * http://www.sencha.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             field,
480             value;
481         fs.each(function(f){
482             field = this.findField(f.name);
483             if(field){
484                 value = field.getValue();
485                 if (typeof value != undefined && value.getGroupValue) {
486                     value = value.getGroupValue();
487                 } else if ( field.eachItem ) {
488                     value = [];
489                     field.eachItem(function(item){
490                         value.push(item.getValue());
491                     });
492                 }
493                 record.set(f.name, value);
494             }
495         }, this);
496         record.endEdit();
497         return this;
498     },
499
500     /**
501      * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
502      * {@link Ext.data.Record#data record data}.
503      * See also {@link #trackResetOnLoad}.
504      * @param {Record} record The record to load
505      * @return {BasicForm} this
506      */
507     loadRecord : function(record){
508         this.setValues(record.data);
509         return this;
510     },
511
512     // private
513     beforeAction : function(action){
514         // Call HtmlEditor's syncValue before actions
515         this.items.each(function(f){
516             if(f.isFormField && f.syncValue){
517                 f.syncValue();
518             }
519         });
520         var o = action.options;
521         if(o.waitMsg){
522             if(this.waitMsgTarget === true){
523                 this.el.mask(o.waitMsg, 'x-mask-loading');
524             }else if(this.waitMsgTarget){
525                 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
526                 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
527             }else{
528                 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
529             }
530         }
531     },
532
533     // private
534     afterAction : function(action, success){
535         this.activeAction = null;
536         var o = action.options;
537         if(o.waitMsg){
538             if(this.waitMsgTarget === true){
539                 this.el.unmask();
540             }else if(this.waitMsgTarget){
541                 this.waitMsgTarget.unmask();
542             }else{
543                 Ext.MessageBox.updateProgress(1);
544                 Ext.MessageBox.hide();
545             }
546         }
547         if(success){
548             if(o.reset){
549                 this.reset();
550             }
551             Ext.callback(o.success, o.scope, [this, action]);
552             this.fireEvent('actioncomplete', this, action);
553         }else{
554             Ext.callback(o.failure, o.scope, [this, action]);
555             this.fireEvent('actionfailed', this, action);
556         }
557     },
558
559     /**
560      * Find a {@link Ext.form.Field} in this form.
561      * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
562      * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
563      * @return Field
564      */
565     findField : function(id) {
566         var field = this.items.get(id);
567
568         if (!Ext.isObject(field)) {
569             //searches for the field corresponding to the given id. Used recursively for composite fields
570             var findMatchingField = function(f) {
571                 if (f.isFormField) {
572                     if (f.dataIndex == id || f.id == id || f.getName() == id) {
573                         field = f;
574                         return false;
575                     } else if (f.isComposite) {
576                         return f.items.each(findMatchingField);
577                     } else if (f instanceof Ext.form.CheckboxGroup && f.rendered) {
578                         return f.eachItem(findMatchingField);
579                     }
580                 }
581             };
582
583             this.items.each(findMatchingField);
584         }
585         return field || null;
586     },
587
588
589     /**
590      * Mark fields in this form invalid in bulk.
591      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
592      * @return {BasicForm} this
593      */
594     markInvalid : function(errors){
595         if (Ext.isArray(errors)) {
596             for(var i = 0, len = errors.length; i < len; i++){
597                 var fieldError = errors[i];
598                 var f = this.findField(fieldError.id);
599                 if(f){
600                     f.markInvalid(fieldError.msg);
601                 }
602             }
603         } else {
604             var field, id;
605             for(id in errors){
606                 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
607                     field.markInvalid(errors[id]);
608                 }
609             }
610         }
611
612         return this;
613     },
614
615     /**
616      * Set values for fields in this form in bulk.
617      * @param {Array/Object} values Either an array in the form:<pre><code>
618 [{id:'clientName', value:'Fred. Olsen Lines'},
619  {id:'portOfLoading', value:'FXT'},
620  {id:'portOfDischarge', value:'OSL'} ]</code></pre>
621      * or an object hash of the form:<pre><code>
622 {
623     clientName: 'Fred. Olsen Lines',
624     portOfLoading: 'FXT',
625     portOfDischarge: 'OSL'
626 }</code></pre>
627      * @return {BasicForm} this
628      */
629     setValues : function(values){
630         if(Ext.isArray(values)){ // array of objects
631             for(var i = 0, len = values.length; i < len; i++){
632                 var v = values[i];
633                 var f = this.findField(v.id);
634                 if(f){
635                     f.setValue(v.value);
636                     if(this.trackResetOnLoad){
637                         f.originalValue = f.getValue();
638                     }
639                 }
640             }
641         }else{ // object hash
642             var field, id;
643             for(id in values){
644                 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
645                     field.setValue(values[id]);
646                     if(this.trackResetOnLoad){
647                         field.originalValue = field.getValue();
648                     }
649                 }
650             }
651         }
652         return this;
653     },
654
655     /**
656      * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
657      * If multiple fields exist with the same name they are returned as an array.</p>
658      * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
659      * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
660      * value can potentially be the emptyText of a field.</p>
661      * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
662      * @return {String/Object}
663      */
664     getValues : function(asString){
665         var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
666         if(asString === true){
667             return fs;
668         }
669         return Ext.urlDecode(fs);
670     },
671
672     /**
673      * Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
674      * If multiple fields exist with the same name they are returned as an array.
675      * @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
676      * @return {Object} The values in the form
677      */
678     getFieldValues : function(dirtyOnly){
679         var o = {},
680             n,
681             key,
682             val;
683         this.items.each(function(f) {
684             if (!f.disabled && (dirtyOnly !== true || f.isDirty())) {
685                 n = f.getName();
686                 key = o[n];
687                 val = f.getValue();
688
689                 if(Ext.isDefined(key)){
690                     if(Ext.isArray(key)){
691                         o[n].push(val);
692                     }else{
693                         o[n] = [key, val];
694                     }
695                 }else{
696                     o[n] = val;
697                 }
698             }
699         });
700         return o;
701     },
702
703     /**
704      * Clears all invalid messages in this form.
705      * @return {BasicForm} this
706      */
707     clearInvalid : function(){
708         this.items.each(function(f){
709            f.clearInvalid();
710         });
711         return this;
712     },
713
714     /**
715      * Resets this form.
716      * @return {BasicForm} this
717      */
718     reset : function(){
719         this.items.each(function(f){
720             f.reset();
721         });
722         return this;
723     },
724
725     /**
726      * Add Ext.form Components to this form's Collection. This does not result in rendering of
727      * the passed Component, it just enables the form to validate Fields, and distribute values to
728      * Fields.
729      * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
730      * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
731      * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
732      * collection.</b></p>
733      * @param {Field} field1
734      * @param {Field} field2 (optional)
735      * @param {Field} etc (optional)
736      * @return {BasicForm} this
737      */
738     add : function(){
739         this.items.addAll(Array.prototype.slice.call(arguments, 0));
740         return this;
741     },
742
743     /**
744      * Removes a field from the items collection (does NOT remove its markup).
745      * @param {Field} field
746      * @return {BasicForm} this
747      */
748     remove : function(field){
749         this.items.remove(field);
750         return this;
751     },
752
753     /**
754      * Removes all fields from the collection that have been destroyed.
755      */
756     cleanDestroyed : function() {
757         this.items.filterBy(function(o) { return !!o.isDestroyed; }).each(this.remove, this);
758     },
759
760     /**
761      * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
762      * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
763      * @return {BasicForm} this
764      */
765     render : function(){
766         this.items.each(function(f){
767             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
768                 f.applyToMarkup(f.id);
769             }
770         });
771         return this;
772     },
773
774     /**
775      * Calls {@link Ext#apply} for all fields in this form with the passed object.
776      * @param {Object} values
777      * @return {BasicForm} this
778      */
779     applyToFields : function(o){
780         this.items.each(function(f){
781            Ext.apply(f, o);
782         });
783         return this;
784     },
785
786     /**
787      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
788      * @param {Object} values
789      * @return {BasicForm} this
790      */
791     applyIfToFields : function(o){
792         this.items.each(function(f){
793            Ext.applyIf(f, o);
794         });
795         return this;
796     },
797
798     callFieldMethod : function(fnName, args){
799         args = args || [];
800         this.items.each(function(f){
801             if(Ext.isFunction(f[fnName])){
802                 f[fnName].apply(f, args);
803             }
804         });
805         return this;
806     }
807 });
808
809 // back compat
810 Ext.BasicForm = Ext.form.BasicForm;