3 * Copyright(c) 2006-2010 Ext JS, LLC
5 * http://www.extjs.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 destroy: function() {
283 this.items.each(function(f){
287 this.el.removeAllListeners();
290 this.purgeListeners();
294 * Returns true if client-side validation on the form is successful.
297 isValid : function(){
299 this.items.each(function(f){
308 * <p>Returns true if any fields in this form have changed from their original values.</p>
309 * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
310 * Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
311 * or {@link #loadRecord}.</p>
314 isDirty : function(){
316 this.items.each(function(f){
326 * Performs a predefined action ({@link Ext.form.Action.Submit} or
327 * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
328 * to perform application-specific processing.
329 * @param {String/Object} actionName The name of the predefined action type,
330 * or instance of {@link Ext.form.Action} to perform.
331 * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
332 * All of the config options listed below are supported by both the
333 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
334 * actions unless otherwise noted (custom actions could also accept
335 * other config options):<ul>
337 * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
338 * to the form's {@link #url}.)</div></li>
340 * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
341 * to the form's method, or POST if not defined)</div></li>
343 * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
344 * (defaults to the form's baseParams, or none if not defined)</p>
345 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
347 * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
348 * (defaults to the form's default headers)</div></li>
350 * <li><b>success</b> : Function<div class="sub-desc">The callback that will
351 * be invoked after a successful response (see top of
352 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
353 * for a description of what constitutes a successful response).
354 * The function is passed the following parameters:<ul>
355 * <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
356 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
357 * <div class="sub-desc">The action object contains these properties of interest:<ul>
358 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
359 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
360 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
361 * </ul></div></li></ul></div></li>
363 * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
364 * failed transaction attempt. The function is passed the following parameters:<ul>
365 * <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
366 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
367 * <div class="sub-desc">The action object contains these properties of interest:<ul>
368 * <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
369 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
370 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
371 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
372 * </ul></div></li></ul></div></li>
374 * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
375 * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
377 * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
378 * Determines whether a Form's fields are validated in a final call to
379 * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
380 * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
382 * @return {BasicForm} this
384 doAction : function(action, options){
385 if(Ext.isString(action)){
386 action = new Ext.form.Action.ACTION_TYPES[action](this, options);
388 if(this.fireEvent('beforeaction', this, action) !== false){
389 this.beforeAction(action);
390 action.run.defer(100, action);
396 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
397 * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
398 * <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
399 * <p>The following code:</p><pre><code>
400 myFormPanel.getForm().submit({
401 clientValidation: true,
402 url: 'updateConsignment.php',
404 newStatus: 'delivered'
406 success: function(form, action) {
407 Ext.Msg.alert('Success', action.result.msg);
409 failure: function(form, action) {
410 switch (action.failureType) {
411 case Ext.form.Action.CLIENT_INVALID:
412 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
414 case Ext.form.Action.CONNECT_FAILURE:
415 Ext.Msg.alert('Failure', 'Ajax communication failed');
417 case Ext.form.Action.SERVER_INVALID:
418 Ext.Msg.alert('Failure', action.result.msg);
423 * would process the following server response for a successful submission:<pre><code>
425 "success":true, // note this is Boolean, not string
426 "msg":"Consignment updated"
429 * and the following server response for a failed submission:<pre><code>
431 "success":false, // note this is Boolean, not string
432 "msg":"You do not have permission to perform this operation"
435 * @return {BasicForm} this
437 submit : function(options){
438 if(this.standardSubmit){
439 var v = this.isValid();
441 var el = this.el.dom;
442 if(this.url && Ext.isEmpty(el.action)){
443 el.action = this.url;
449 var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
450 this.doAction(submitAction, options);
455 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
456 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
457 * @return {BasicForm} this
459 load : function(options){
460 var loadAction = String.format('{0}load', this.api ? 'direct' : '');
461 this.doAction(loadAction, options);
466 * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
467 * @param {Record} record The record to edit
468 * @return {BasicForm} this
470 updateRecord : function(record){
472 var fs = record.fields;
474 var field = this.findField(f.name);
476 record.set(f.name, field.getValue());
484 * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
485 * {@link Ext.data.Record#data record data}.
486 * See also {@link #trackResetOnLoad}.
487 * @param {Record} record The record to load
488 * @return {BasicForm} this
490 loadRecord : function(record){
491 this.setValues(record.data);
496 beforeAction : function(action){
497 var o = action.options;
499 if(this.waitMsgTarget === true){
500 this.el.mask(o.waitMsg, 'x-mask-loading');
501 }else if(this.waitMsgTarget){
502 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
503 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
505 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
511 afterAction : function(action, success){
512 this.activeAction = null;
513 var o = action.options;
515 if(this.waitMsgTarget === true){
517 }else if(this.waitMsgTarget){
518 this.waitMsgTarget.unmask();
520 Ext.MessageBox.updateProgress(1);
521 Ext.MessageBox.hide();
528 Ext.callback(o.success, o.scope, [this, action]);
529 this.fireEvent('actioncomplete', this, action);
531 Ext.callback(o.failure, o.scope, [this, action]);
532 this.fireEvent('actionfailed', this, action);
537 * Find a {@link Ext.form.Field} in this form.
538 * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
539 * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
542 findField : function(id){
543 var field = this.items.get(id);
544 if(!Ext.isObject(field)){
545 this.items.each(function(f){
546 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
552 return field || null;
557 * Mark fields in this form invalid in bulk.
558 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
559 * @return {BasicForm} this
561 markInvalid : function(errors){
562 if(Ext.isArray(errors)){
563 for(var i = 0, len = errors.length; i < len; i++){
564 var fieldError = errors[i];
565 var f = this.findField(fieldError.id);
567 f.markInvalid(fieldError.msg);
573 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
574 field.markInvalid(errors[id]);
582 * Set values for fields in this form in bulk.
583 * @param {Array/Object} values Either an array in the form:<pre><code>
584 [{id:'clientName', value:'Fred. Olsen Lines'},
585 {id:'portOfLoading', value:'FXT'},
586 {id:'portOfDischarge', value:'OSL'} ]</code></pre>
587 * or an object hash of the form:<pre><code>
589 clientName: 'Fred. Olsen Lines',
590 portOfLoading: 'FXT',
591 portOfDischarge: 'OSL'
593 * @return {BasicForm} this
595 setValues : function(values){
596 if(Ext.isArray(values)){ // array of objects
597 for(var i = 0, len = values.length; i < len; i++){
599 var f = this.findField(v.id);
602 if(this.trackResetOnLoad){
603 f.originalValue = f.getValue();
607 }else{ // object hash
610 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
611 field.setValue(values[id]);
612 if(this.trackResetOnLoad){
613 field.originalValue = field.getValue();
622 * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
623 * If multiple fields exist with the same name they are returned as an array.</p>
624 * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
625 * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
626 * value can potentially be the emptyText of a field.</p>
627 * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
628 * @return {String/Object}
630 getValues : function(asString){
631 var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
632 if(asString === true){
635 return Ext.urlDecode(fs);
639 * Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
640 * If multiple fields exist with the same name they are returned as an array.
641 * @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
642 * @return {Object} The values in the form
644 getFieldValues : function(dirtyOnly){
649 this.items.each(function(f){
650 if(dirtyOnly !== true || f.isDirty()){
655 if(Ext.isDefined(key)){
656 if(Ext.isArray(key)){
670 * Clears all invalid messages in this form.
671 * @return {BasicForm} this
673 clearInvalid : function(){
674 this.items.each(function(f){
682 * @return {BasicForm} this
685 this.items.each(function(f){
692 * Add Ext.form Components to this form's Collection. This does not result in rendering of
693 * the passed Component, it just enables the form to validate Fields, and distribute values to
695 * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
696 * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
697 * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
698 * collection.</b></p>
699 * @param {Field} field1
700 * @param {Field} field2 (optional)
701 * @param {Field} etc (optional)
702 * @return {BasicForm} this
705 this.items.addAll(Array.prototype.slice.call(arguments, 0));
711 * Removes a field from the items collection (does NOT remove its markup).
712 * @param {Field} field
713 * @return {BasicForm} this
715 remove : function(field){
716 this.items.remove(field);
721 * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
722 * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
723 * @return {BasicForm} this
726 this.items.each(function(f){
727 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
728 f.applyToMarkup(f.id);
735 * Calls {@link Ext#apply} for all fields in this form with the passed object.
736 * @param {Object} values
737 * @return {BasicForm} this
739 applyToFields : function(o){
740 this.items.each(function(f){
747 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
748 * @param {Object} values
749 * @return {BasicForm} this
751 applyIfToFields : function(o){
752 this.items.each(function(f){
758 callFieldMethod : function(fnName, args){
760 this.items.each(function(f){
761 if(Ext.isFunction(f[fnName])){
762 f[fnName].apply(f, args);
770 Ext.BasicForm = Ext.form.BasicForm;