3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.com/license
8 * @class Ext.form.BasicForm
9 * @extends Ext.util.Observable
10 * <p>Encapsulates the DOM <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><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><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 * "<" as "&lt;", "&" as "&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>
34 * @param {Mixed} el The form element or its id
35 * @param {Object} config Configuration options
37 Ext.form.BasicForm = Ext.extend(Ext.util.Observable, {
39 constructor: function(el, config){
40 Ext.apply(this, config);
41 if(Ext.isString(this.paramOrder)){
42 this.paramOrder = this.paramOrder.split(/[\s,|]/);
45 * A {@link Ext.util.MixedCollection MixedCollection} containing all the Ext.form.Fields in this form.
46 * @type MixedCollection
49 this.items = new Ext.util.MixedCollection(false, function(o){
55 * Fires before any action is performed. Return false to cancel the action.
57 * @param {Action} action The {@link Ext.form.Action} to be performed
62 * Fires when an action fails.
64 * @param {Action} action The {@link Ext.form.Action} that failed
68 * @event actioncomplete
69 * Fires when an action is completed.
71 * @param {Action} action The {@link Ext.form.Action} that completed
79 Ext.form.BasicForm.superclass.constructor.call(this);
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.
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.
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>
112 * The URL to use for form actions if one isn't supplied in the
113 * <code>{@link #doAction doAction} options</code>.
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><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><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 * "<" as "&lt;", "&" as "&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>
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>
143 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
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
152 * Such as the following:<pre><code>
154 load: App.ss.MyProfile.load,
155 submit: App.ss.MyProfile.submit
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>
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'
178 paramOrder: undefined,
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.
189 * @cfg {String} waitTitle
190 * The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
192 waitTitle: 'Please Wait...',
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>.
201 trackResetOnLoad : false,
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>
214 standardSubmit: true,
218 {@link url}: 'myProcess.php',
226 var fp = this.ownerCt.ownerCt,
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) {
237 value: fp.baseParams[i]
241 // set a custom flag to prevent re-adding
242 fp.paramsAdded = true;
244 form.{@link #submit}();
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.
255 * @property waitMsgTarget
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);
265 this.el.addClass('x-form');
269 * Get the HTML form Element
270 * @return Ext.Element
277 onSubmit : function(e){
282 * Destroys this object.
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.
287 destroy: function(bound){
289 this.items.each(function(f){
292 Ext.destroy(this.el);
295 this.purgeListeners();
299 * Returns true if client-side validation on the form is successful.
302 isValid : function(){
304 this.items.each(function(f){
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>
319 isDirty : function(){
321 this.items.each(function(f){
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>
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>
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>
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>
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>
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>
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>
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>
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>
387 * @return {BasicForm} this
389 doAction : function(action, options){
390 if(Ext.isString(action)){
391 action = new Ext.form.Action.ACTION_TYPES[action](this, options);
393 if(this.fireEvent('beforeaction', this, action) !== false){
394 this.beforeAction(action);
395 action.run.defer(100, action);
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',
409 newStatus: 'delivered'
411 success: function(form, action) {
412 Ext.Msg.alert('Success', action.result.msg);
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');
419 case Ext.form.Action.CONNECT_FAILURE:
420 Ext.Msg.alert('Failure', 'Ajax communication failed');
422 case Ext.form.Action.SERVER_INVALID:
423 Ext.Msg.alert('Failure', action.result.msg);
428 * would process the following server response for a successful submission:<pre><code>
430 "success":true, // note this is Boolean, not string
431 "msg":"Consignment updated"
434 * and the following server response for a failed submission:<pre><code>
436 "success":false, // note this is Boolean, not string
437 "msg":"You do not have permission to perform this operation"
440 * @return {BasicForm} this
442 submit : function(options){
443 options = options || {};
444 if(this.standardSubmit){
445 var v = options.clientValidation === false || this.isValid();
447 var el = this.el.dom;
448 if(this.url && Ext.isEmpty(el.action)){
449 el.action = this.url;
455 var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
456 this.doAction(submitAction, options);
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
465 load : function(options){
466 var loadAction = String.format('{0}load', this.api ? 'direct' : '');
467 this.doAction(loadAction, options);
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
476 updateRecord : function(record){
478 var fs = record.fields,
482 field = this.findField(f.name);
484 value = field.getValue();
485 if (typeof value != undefined && value.getGroupValue) {
486 value = value.getGroupValue();
487 } else if ( field.eachItem ) {
489 field.eachItem(function(item){
490 value.push(item.getValue());
493 record.set(f.name, value);
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
507 loadRecord : function(record){
508 this.setValues(record.data);
513 beforeAction : function(action){
514 // Call HtmlEditor's syncValue before actions
515 this.items.each(function(f){
516 if(f.isFormField && f.syncValue){
520 var o = action.options;
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');
528 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
534 afterAction : function(action, success){
535 this.activeAction = null;
536 var o = action.options;
538 if(this.waitMsgTarget === true){
540 }else if(this.waitMsgTarget){
541 this.waitMsgTarget.unmask();
543 Ext.MessageBox.updateProgress(1);
544 Ext.MessageBox.hide();
551 Ext.callback(o.success, o.scope, [this, action]);
552 this.fireEvent('actioncomplete', this, action);
554 Ext.callback(o.failure, o.scope, [this, action]);
555 this.fireEvent('actionfailed', this, action);
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}).
565 findField : function(id) {
566 var field = this.items.get(id);
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) {
572 if (f.dataIndex == id || f.id == id || f.getName() == id) {
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);
583 this.items.each(findMatchingField);
585 return field || null;
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
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);
600 f.markInvalid(fieldError.msg);
606 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
607 field.markInvalid(errors[id]);
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>
623 clientName: 'Fred. Olsen Lines',
624 portOfLoading: 'FXT',
625 portOfDischarge: 'OSL'
627 * @return {BasicForm} this
629 setValues : function(values){
630 if(Ext.isArray(values)){ // array of objects
631 for(var i = 0, len = values.length; i < len; i++){
633 var f = this.findField(v.id);
636 if(this.trackResetOnLoad){
637 f.originalValue = f.getValue();
641 }else{ // object hash
644 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
645 field.setValue(values[id]);
646 if(this.trackResetOnLoad){
647 field.originalValue = field.getValue();
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}
664 getValues : function(asString){
665 var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
666 if(asString === true){
669 return Ext.urlDecode(fs);
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
678 getFieldValues : function(dirtyOnly){
683 this.items.each(function(f) {
684 if (!f.disabled && (dirtyOnly !== true || f.isDirty())) {
689 if(Ext.isDefined(key)){
690 if(Ext.isArray(key)){
704 * Clears all invalid messages in this form.
705 * @return {BasicForm} this
707 clearInvalid : function(){
708 this.items.each(function(f){
716 * @return {BasicForm} this
719 this.items.each(function(f){
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
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
739 this.items.addAll(Array.prototype.slice.call(arguments, 0));
744 * Removes a field from the items collection (does NOT remove its markup).
745 * @param {Field} field
746 * @return {BasicForm} this
748 remove : function(field){
749 this.items.remove(field);
754 * Removes all fields from the collection that have been destroyed.
756 cleanDestroyed : function() {
757 this.items.filterBy(function(o) { return !!o.isDestroyed; }).each(this.remove, this);
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
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);
775 * Calls {@link Ext#apply} for all fields in this form with the passed object.
776 * @param {Object} values
777 * @return {BasicForm} this
779 applyToFields : function(o){
780 this.items.each(function(f){
787 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
788 * @param {Object} values
789 * @return {BasicForm} this
791 applyIfToFields : function(o){
792 this.items.each(function(f){
798 callFieldMethod : function(fnName, args){
800 this.items.each(function(f){
801 if(Ext.isFunction(f[fnName])){
802 f[fnName].apply(f, args);
810 Ext.BasicForm = Ext.form.BasicForm;