3 * Copyright(c) 2006-2009 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 = function(el, config){
38 Ext.apply(this, config);
39 if(Ext.isString(this.paramOrder)){
40 this.paramOrder = this.paramOrder.split(/[\s,|]/);
44 * A {@link Ext.util.MixedCollection MixedCollection) containing all the Ext.form.Fields in this form.
45 * @type MixedCollection
47 this.items = new Ext.util.MixedCollection(false, function(o){
53 * Fires before any action is performed. Return false to cancel the action.
55 * @param {Action} action The {@link Ext.form.Action} to be performed
60 * Fires when an action fails.
62 * @param {Action} action The {@link Ext.form.Action} that failed
66 * @event actioncomplete
67 * Fires when an action is completed.
69 * @param {Action} action The {@link Ext.form.Action} that completed
77 Ext.form.BasicForm.superclass.constructor.call(this);
80 Ext.extend(Ext.form.BasicForm, Ext.util.Observable, {
82 * @cfg {String} method
83 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
86 * @cfg {DataReader} reader
87 * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read
88 * data when executing 'load' actions. This is optional as there is built-in
89 * support for processing JSON. For additional information on using an XMLReader
90 * see the example provided in examples/form/xml-form.html.
93 * @cfg {DataReader} errorReader
94 * <p>An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to
95 * read field error messages returned from 'submit' actions. This is optional
96 * as there is built-in support for processing JSON.</p>
97 * <p>The Records which provide messages for the invalid Fields must use the
98 * Field name (or id) as the Record ID, and must contain a field called 'msg'
99 * which contains the error message.</p>
100 * <p>The errorReader does not have to be a full-blown implementation of a
101 * DataReader. It simply needs to implement a <tt>read(xhr)</tt> function
102 * which returns an Array of Records in an object with the following
103 * structure:</p><pre><code>
111 * The URL to use for form actions if one isn't supplied in the
112 * <code>{@link #doAction doAction} options</code>.
115 * @cfg {Boolean} fileUpload
116 * Set to true if this form is a file upload.
117 * <p>File uploads are not performed using normal 'Ajax' techniques, that is they are <b>not</b>
118 * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
119 * DOM <tt><form></tt> element temporarily modified to have its
120 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
121 * to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
122 * but removed after the return data has been gathered.</p>
123 * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
124 * server is using JSON to send the return object, then the
125 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
126 * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
127 * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
128 * "<" as "&lt;", "&" as "&amp;" etc.</p>
129 * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
130 * is created containing a <tt>responseText</tt> property in order to conform to the
131 * requirements of event handlers and callbacks.</p>
132 * <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>
133 * and some server technologies (notably JEE) may require some custom processing in order to
134 * retrieve parameter names and parameter values from the packet content.</p>
137 * @cfg {Object} baseParams
138 * <p>Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.</p>
139 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
142 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
147 * @cfg {Object} api (Optional) If specified load and submit actions will be handled
148 * with {@link Ext.form.Action.DirectLoad} and {@link Ext.form.Action.DirectSubmit}.
149 * Methods which have been imported by Ext.Direct can be specified here to load and submit
151 * Such as the following:<pre><code>
153 load: App.ss.MyProfile.load,
154 submit: App.ss.MyProfile.submit
157 * <p>Load actions can use <code>{@link #paramOrder}</code> or <code>{@link #paramsAsHash}</code>
158 * to customize how the load method is invoked.
159 * Submit actions will always use a standard form submit. The formHandler configuration must
160 * be set on the associated server-side method which has been imported by Ext.Direct</p>
164 * @cfg {Array/String} paramOrder <p>A list of params to be executed server side.
165 * Defaults to <tt>undefined</tt>. Only used for the <code>{@link #api}</code>
166 * <code>load</code> configuration.</p>
167 * <br><p>Specify the params in the order in which they must be executed on the
168 * server-side as either (1) an Array of String values, or (2) a String of params
169 * delimited by either whitespace, comma, or pipe. For example,
170 * any of the following would be acceptable:</p><pre><code>
171 paramOrder: ['param1','param2','param3']
172 paramOrder: 'param1 param2 param3'
173 paramOrder: 'param1,param2,param3'
174 paramOrder: 'param1|param2|param'
177 paramOrder: undefined,
180 * @cfg {Boolean} paramsAsHash Only used for the <code>{@link #api}</code>
181 * <code>load</code> configuration. Send parameters as a collection of named
182 * arguments (defaults to <tt>false</tt>). Providing a
183 * <tt>{@link #paramOrder}</tt> nullifies this configuration.
188 * @cfg {String} waitTitle
189 * The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
191 waitTitle: 'Please Wait...',
197 * @cfg {Boolean} trackResetOnLoad If set to <tt>true</tt>, {@link #reset}() resets to the last loaded
198 * or {@link #setValues}() data instead of when the form was first created. Defaults to <tt>false</tt>.
200 trackResetOnLoad : false,
203 * @cfg {Boolean} standardSubmit
204 * <p>If set to <tt>true</tt>, standard HTML form submits are used instead
205 * of XHR (Ajax) style form submissions. Defaults to <tt>false</tt>.</p>
206 * <br><p><b>Note:</b> When using <code>standardSubmit</code>, the
207 * <code>options</code> to <code>{@link #submit}</code> are ignored because
208 * Ext's Ajax infrastracture is bypassed. To pass extra parameters (e.g.
209 * <code>baseParams</code> and <code>params</code>), utilize hidden fields
210 * to submit extra data, for example:</p>
213 standardSubmit: true,
217 {@link url}: 'myProcess.php',
225 var fp = this.ownerCt.ownerCt,
227 if (form.isValid()) {
228 // check if there are baseParams and if
229 // hiddent items have been added already
230 if (fp.baseParams && !fp.paramsAdded) {
231 // add hidden items for all baseParams
232 for (i in fp.baseParams) {
236 value: fp.baseParams[i]
240 // set a custom flag to prevent re-adding
241 fp.paramsAdded = true;
243 form.{@link #submit}();
251 * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
252 * element by passing it or its id or mask the form itself by passing in true.
254 * @property waitMsgTarget
258 initEl : function(el){
259 this.el = Ext.get(el);
260 this.id = this.el.id || Ext.id();
261 if(!this.standardSubmit){
262 this.el.on('submit', this.onSubmit, this);
264 this.el.addClass('x-form');
268 * Get the HTML form Element
269 * @return Ext.Element
276 onSubmit : function(e){
281 destroy: function() {
282 this.items.each(function(f){
286 this.el.removeAllListeners();
289 this.purgeListeners();
293 * Returns true if client-side validation on the form is successful.
296 isValid : function(){
298 this.items.each(function(f){
307 * <p>Returns true if any fields in this form have changed from their original values.</p>
308 * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
309 * Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
310 * or {@link #loadRecord}.</p>
313 isDirty : function(){
315 this.items.each(function(f){
325 * Performs a predefined action ({@link Ext.form.Action.Submit} or
326 * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
327 * to perform application-specific processing.
328 * @param {String/Object} actionName The name of the predefined action type,
329 * or instance of {@link Ext.form.Action} to perform.
330 * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
331 * All of the config options listed below are supported by both the
332 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
333 * actions unless otherwise noted (custom actions could also accept
334 * other config options):<ul>
336 * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
337 * to the form's {@link #url}.)</div></li>
339 * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
340 * to the form's method, or POST if not defined)</div></li>
342 * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
343 * (defaults to the form's baseParams, or none if not defined)</p>
344 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
346 * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
347 * (defaults to the form's default headers)</div></li>
349 * <li><b>success</b> : Function<div class="sub-desc">The callback that will
350 * be invoked after a successful response (see top of
351 * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
352 * for a description of what constitutes a successful response).
353 * The function is passed the following parameters:<ul>
354 * <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
355 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
356 * <div class="sub-desc">The action object contains these properties of interest:<ul>
357 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
358 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
359 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
360 * </ul></div></li></ul></div></li>
362 * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
363 * failed transaction attempt. The function is passed the following parameters:<ul>
364 * <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
365 * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
366 * <div class="sub-desc">The action object contains these properties of interest:<ul>
367 * <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
368 * <li><tt>{@link Ext.form.Action#response response}</tt></li>
369 * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
370 * <li><tt>{@link Ext.form.Action#type type}</tt></li>
371 * </ul></div></li></ul></div></li>
373 * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
374 * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
376 * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
377 * Determines whether a Form's fields are validated in a final call to
378 * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
379 * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
381 * @return {BasicForm} this
383 doAction : function(action, options){
384 if(Ext.isString(action)){
385 action = new Ext.form.Action.ACTION_TYPES[action](this, options);
387 if(this.fireEvent('beforeaction', this, action) !== false){
388 this.beforeAction(action);
389 action.run.defer(100, action);
395 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
396 * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
397 * <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
398 * <p>The following code:</p><pre><code>
399 myFormPanel.getForm().submit({
400 clientValidation: true,
401 url: 'updateConsignment.php',
403 newStatus: 'delivered'
405 success: function(form, action) {
406 Ext.Msg.alert('Success', action.result.msg);
408 failure: function(form, action) {
409 switch (action.failureType) {
410 case Ext.form.Action.CLIENT_INVALID:
411 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
413 case Ext.form.Action.CONNECT_FAILURE:
414 Ext.Msg.alert('Failure', 'Ajax communication failed');
416 case Ext.form.Action.SERVER_INVALID:
417 Ext.Msg.alert('Failure', action.result.msg);
422 * would process the following server response for a successful submission:<pre><code>
424 "success":true, // note this is Boolean, not string
425 "msg":"Consignment updated"
428 * and the following server response for a failed submission:<pre><code>
430 "success":false, // note this is Boolean, not string
431 "msg":"You do not have permission to perform this operation"
434 * @return {BasicForm} this
436 submit : function(options){
437 if(this.standardSubmit){
438 var v = this.isValid();
440 var el = this.el.dom;
441 if(this.url && Ext.isEmpty(el.action)){
442 el.action = this.url;
448 var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
449 this.doAction(submitAction, options);
454 * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
455 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
456 * @return {BasicForm} this
458 load : function(options){
459 var loadAction = String.format('{0}load', this.api ? 'direct' : '');
460 this.doAction(loadAction, options);
465 * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
466 * @param {Record} record The record to edit
467 * @return {BasicForm} this
469 updateRecord : function(record){
471 var fs = record.fields;
473 var field = this.findField(f.name);
475 record.set(f.name, field.getValue());
483 * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
484 * {@link Ext.data.Record#data record data}.
485 * See also {@link #trackResetOnLoad}.
486 * @param {Record} record The record to load
487 * @return {BasicForm} this
489 loadRecord : function(record){
490 this.setValues(record.data);
495 beforeAction : function(action){
496 var o = action.options;
498 if(this.waitMsgTarget === true){
499 this.el.mask(o.waitMsg, 'x-mask-loading');
500 }else if(this.waitMsgTarget){
501 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
502 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
504 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
510 afterAction : function(action, success){
511 this.activeAction = null;
512 var o = action.options;
514 if(this.waitMsgTarget === true){
516 }else if(this.waitMsgTarget){
517 this.waitMsgTarget.unmask();
519 Ext.MessageBox.updateProgress(1);
520 Ext.MessageBox.hide();
527 Ext.callback(o.success, o.scope, [this, action]);
528 this.fireEvent('actioncomplete', this, action);
530 Ext.callback(o.failure, o.scope, [this, action]);
531 this.fireEvent('actionfailed', this, action);
536 * Find a {@link Ext.form.Field} in this form.
537 * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
538 * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
541 findField : function(id){
542 var field = this.items.get(id);
543 if(!Ext.isObject(field)){
544 this.items.each(function(f){
545 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
551 return field || null;
556 * Mark fields in this form invalid in bulk.
557 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
558 * @return {BasicForm} this
560 markInvalid : function(errors){
561 if(Ext.isArray(errors)){
562 for(var i = 0, len = errors.length; i < len; i++){
563 var fieldError = errors[i];
564 var f = this.findField(fieldError.id);
566 f.markInvalid(fieldError.msg);
572 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
573 field.markInvalid(errors[id]);
581 * Set values for fields in this form in bulk.
582 * @param {Array/Object} values Either an array in the form:<pre><code>
583 [{id:'clientName', value:'Fred. Olsen Lines'},
584 {id:'portOfLoading', value:'FXT'},
585 {id:'portOfDischarge', value:'OSL'} ]</code></pre>
586 * or an object hash of the form:<pre><code>
588 clientName: 'Fred. Olsen Lines',
589 portOfLoading: 'FXT',
590 portOfDischarge: 'OSL'
592 * @return {BasicForm} this
594 setValues : function(values){
595 if(Ext.isArray(values)){ // array of objects
596 for(var i = 0, len = values.length; i < len; i++){
598 var f = this.findField(v.id);
601 if(this.trackResetOnLoad){
602 f.originalValue = f.getValue();
606 }else{ // object hash
609 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
610 field.setValue(values[id]);
611 if(this.trackResetOnLoad){
612 field.originalValue = field.getValue();
621 * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
622 * If multiple fields exist with the same name they are returned as an array.</p>
623 * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
624 * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
625 * value can potentially be the emptyText of a field.</p>
626 * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
627 * @return {String/Object}
629 getValues : function(asString){
630 var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
631 if(asString === true){
634 return Ext.urlDecode(fs);
637 getFieldValues : function(){
639 this.items.each(function(f){
640 o[f.getName()] = f.getValue();
646 * Clears all invalid messages in this form.
647 * @return {BasicForm} this
649 clearInvalid : function(){
650 this.items.each(function(f){
658 * @return {BasicForm} this
661 this.items.each(function(f){
668 * Add Ext.form Components to this form's Collection. This does not result in rendering of
669 * the passed Component, it just enables the form to validate Fields, and distribute values to
671 * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
672 * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
673 * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
674 * collection.</b></p>
675 * @param {Field} field1
676 * @param {Field} field2 (optional)
677 * @param {Field} etc (optional)
678 * @return {BasicForm} this
681 this.items.addAll(Array.prototype.slice.call(arguments, 0));
687 * Removes a field from the items collection (does NOT remove its markup).
688 * @param {Field} field
689 * @return {BasicForm} this
691 remove : function(field){
692 this.items.remove(field);
697 * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
698 * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
699 * @return {BasicForm} this
702 this.items.each(function(f){
703 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
704 f.applyToMarkup(f.id);
711 * Calls {@link Ext#apply} for all fields in this form with the passed object.
712 * @param {Object} values
713 * @return {BasicForm} this
715 applyToFields : function(o){
716 this.items.each(function(f){
723 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
724 * @param {Object} values
725 * @return {BasicForm} this
727 applyIfToFields : function(o){
728 this.items.each(function(f){
734 callFieldMethod : function(fnName, args){
736 this.items.each(function(f){
737 if(Ext.isFunction(f[fnName])){
738 f[fnName].apply(f, args);
746 Ext.BasicForm = Ext.form.BasicForm;