Roo/form/BasicForm.js
[roojs1] / Roo / form / BasicForm.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.form.BasicForm
14  * @extends Roo.util.Observable
15  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
16  * @constructor
17  * @param {String/HTMLElement/Roo.Element} el The form element or its id
18  * @param {Object} config Configuration options
19  */
20 Roo.form.BasicForm = function(el, config){
21     this.allItems = [];
22     this.childForms = [];
23     Roo.apply(this, config);
24     /*
25      * The Roo.form.Field items in this form.
26      * @type MixedCollection
27      */
28      
29      
30     this.items = new Roo.util.MixedCollection(false, function(o){
31         return o.id || (o.id = Roo.id());
32     });
33     this.addEvents({
34         /**
35          * @event beforeaction
36          * Fires before any action is performed. Return false to cancel the action.
37          * @param {Form} this
38          * @param {Action} action The action to be performed
39          */
40         beforeaction: true,
41         /**
42          * @event actionfailed
43          * Fires when an action fails.
44          * @param {Form} this
45          * @param {Action} action The action that failed
46          */
47         actionfailed : true,
48         /**
49          * @event actioncomplete
50          * Fires when an action is completed.
51          * @param {Form} this
52          * @param {Action} action The action that completed
53          */
54         actioncomplete : true
55     });
56     if(el){
57         this.initEl(el);
58     }
59     Roo.form.BasicForm.superclass.constructor.call(this);
60 };
61
62 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
63     /**
64      * @cfg {String} method
65      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
66      */
67     /**
68      * @cfg {DataReader} reader
69      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
70      * This is optional as there is built-in support for processing JSON.
71      */
72     /**
73      * @cfg {DataReader} errorReader
74      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
75      * This is completely optional as there is built-in support for processing JSON.
76      */
77     /**
78      * @cfg {String} url
79      * The URL to use for form actions if one isn't supplied in the action options.
80      */
81     /**
82      * @cfg {Boolean} fileUpload
83      * Set to true if this form is a file upload.
84      */
85      
86     /**
87      * @cfg {Object} baseParams
88      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
89      */
90      /**
91      
92     /**
93      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
94      */
95     timeout: 30,
96
97     // private
98     activeAction : null,
99
100     /**
101      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
102      * or setValues() data instead of when the form was first created.
103      */
104     trackResetOnLoad : false,
105     
106     
107     /**
108      * childForms - used for multi-tab forms
109      * @type {Array}
110      */
111     childForms : false,
112     
113     /**
114      * allItems - full list of fields.
115      * @type {Array}
116      */
117     allItems : false,
118     
119     /**
120      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
121      * element by passing it or its id or mask the form itself by passing in true.
122      * @type Mixed
123      */
124     waitMsgTarget : false,
125
126     // private
127     initEl : function(el){
128         this.el = Roo.get(el);
129         this.id = this.el.id || Roo.id();
130         this.el.on('submit', this.onSubmit, this);
131         this.el.addClass('x-form');
132     },
133
134     // private
135     onSubmit : function(e){
136         e.stopEvent();
137     },
138
139     /**
140      * Returns true if client-side validation on the form is successful.
141      * @return Boolean
142      */
143     isValid : function(){
144         var valid = true;
145         this.items.each(function(f){
146            if(!f.validate()){
147                valid = false;
148            }
149         });
150         return valid;
151     },
152
153     /**
154      * Returns true if any fields in this form have changed since their original load.
155      * @return Boolean
156      */
157     isDirty : function(){
158         var dirty = false;
159         this.items.each(function(f){
160            if(f.isDirty()){
161                dirty = true;
162                return false;
163            }
164         });
165         return dirty;
166     },
167
168     /**
169      * Performs a predefined action (submit or load) or custom actions you define on this form.
170      * @param {String} actionName The name of the action type
171      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
172      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
173      * accept other config options):
174      * <pre>
175 Property          Type             Description
176 ----------------  ---------------  ----------------------------------------------------------------------------------
177 url               String           The url for the action (defaults to the form's url)
178 method            String           The form method to use (defaults to the form's method, or POST if not defined)
179 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
180 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
181                                    validate the form on the client (defaults to false)
182      * </pre>
183      * @return {BasicForm} this
184      */
185     doAction : function(action, options){
186         if(typeof action == 'string'){
187             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
188         }
189         if(this.fireEvent('beforeaction', this, action) !== false){
190             this.beforeAction(action);
191             action.run.defer(100, action);
192         }
193         return this;
194     },
195
196     /**
197      * Shortcut to do a submit action.
198      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
199      * @return {BasicForm} this
200      */
201     submit : function(options){
202         this.doAction('submit', options);
203         return this;
204     },
205
206     /**
207      * Shortcut to do a load action.
208      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
209      * @return {BasicForm} this
210      */
211     load : function(options){
212         this.doAction('load', options);
213         return this;
214     },
215
216     /**
217      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
218      * @param {Record} record The record to edit
219      * @return {BasicForm} this
220      */
221     updateRecord : function(record){
222         record.beginEdit();
223         var fs = record.fields;
224         fs.each(function(f){
225             var field = this.findField(f.name);
226             if(field){
227                 record.set(f.name, field.getValue());
228             }
229         }, this);
230         record.endEdit();
231         return this;
232     },
233
234     /**
235      * Loads an Roo.data.Record into this form.
236      * @param {Record} record The record to load
237      * @return {BasicForm} this
238      */
239     loadRecord : function(record){
240         this.setValues(record.data);
241         return this;
242     },
243
244     // private
245     beforeAction : function(action){
246         var o = action.options;
247         
248        
249         if(this.waitMsgTarget === true){
250             this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
251         }else if(this.waitMsgTarget){
252             this.waitMsgTarget = Roo.get(this.waitMsgTarget);
253             this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
254         }else {
255             Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
256         }
257          
258     },
259
260     // private
261     afterAction : function(action, success){
262         this.activeAction = null;
263         var o = action.options;
264         
265         if(this.waitMsgTarget === true){
266             this.el.unmask();
267         }else if(this.waitMsgTarget){
268             this.waitMsgTarget.unmask();
269         }else{
270             Roo.MessageBox.updateProgress(1);
271             Roo.MessageBox.hide();
272         }
273          
274         if(success){
275             if(o.reset){
276                 this.reset();
277             }
278             Roo.callback(o.success, o.scope, [this, action]);
279             this.fireEvent('actioncomplete', this, action);
280             
281         }else{
282             Roo.callback(o.failure, o.scope, [this, action]);
283             // show an error message if no failed handler is set..
284             if (!this.hasListener('actionfailed')) {
285                 Roo.MessageBox.alert("Error",
286                     typeof(action.result.errorMsg) != 'undefined' ?
287                         action.result.errorMsg :
288                         "Saving Failed, please check your entries"
289                 );
290             }
291             
292             this.fireEvent('actionfailed', this, action);
293         }
294         
295     },
296
297     /**
298      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
299      * @param {String} id The value to search for
300      * @return Field
301      */
302     findField : function(id){
303         var field = this.items.get(id);
304         if(!field){
305             this.items.each(function(f){
306                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
307                     field = f;
308                     return false;
309                 }
310             });
311         }
312         return field || null;
313     },
314
315     /**
316      * Add a secondary form to this one, 
317      * Used to provide tabbed forms. One form is primary, with hidden values 
318      * which mirror the elements from the other forms.
319      * 
320      * @param {Roo.form.Form} form to add.
321      * 
322      */
323     addForm : function(form)
324     {
325        
326         if (this.childForms.indexOf(form) > -1) {
327             // already added..
328             return;
329         }
330         this.childForms.push(form);
331         var n = '';
332         Roo.each(form.allItems, function (fe) {
333             
334             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
335             if (this.findField(n)) { // already added..
336                 return;
337             }
338             var add = new Roo.form.Hidden({
339                 name : n
340             });
341             add.render(this.el);
342             
343             this.add( add );
344         }, this);
345         
346     },
347     /**
348      * Mark fields in this form invalid in bulk.
349      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
350      * @return {BasicForm} this
351      */
352     markInvalid : function(errors){
353         if(errors instanceof Array){
354             for(var i = 0, len = errors.length; i < len; i++){
355                 var fieldError = errors[i];
356                 var f = this.findField(fieldError.id);
357                 if(f){
358                     f.markInvalid(fieldError.msg);
359                 }
360             }
361         }else{
362             var field, id;
363             for(id in errors){
364                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
365                     field.markInvalid(errors[id]);
366                 }
367             }
368         }
369         Roo.each(this.childForms || [], function (f) {
370             f.markInvalid(errors);
371         });
372         
373         return this;
374     },
375
376     /**
377      * Set values for fields in this form in bulk.
378      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
379      * @return {BasicForm} this
380      */
381     setValues : function(values){
382         if(values instanceof Array){ // array of objects
383             for(var i = 0, len = values.length; i < len; i++){
384                 var v = values[i];
385                 var f = this.findField(v.id);
386                 if(f){
387                     f.setValue(v.value);
388                     if(this.trackResetOnLoad){
389                         f.originalValue = f.getValue();
390                     }
391                 }
392             }
393         }else{ // object hash
394             var field, id;
395             for(id in values){
396                 if(typeof values[id] != 'function' && (field = this.findField(id))){
397                     
398                     if (field.setFromData && 
399                         field.valueField && 
400                         field.displayField &&
401                         // combos' with local stores can 
402                         // be queried via setValue()
403                         // to set their value..
404                         (field.store && !field.store.isLocal)
405                         ) {
406                         // it's a combo
407                         var sd = { };
408                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
409                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
410                         field.setFromData(sd);
411                         
412                     } else {
413                         field.setValue(values[id]);
414                     }
415                     
416                     
417                     if(this.trackResetOnLoad){
418                         field.originalValue = field.getValue();
419                     }
420                 }
421             }
422         }
423          
424         Roo.each(this.childForms || [], function (f) {
425             f.setValues(values);
426         });
427                 
428         return this;
429     },
430
431     /**
432      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
433      * they are returned as an array.
434      * @param {Boolean} asString
435      * @return {Object}
436      */
437     getValues : function(asString){
438         if (this.childForms) {
439             // copy values from the child forms
440             Roo.each(this.childForms, function (f) {
441                 this.setValues(f.getValues());
442             }, this);
443         }
444         
445         
446         
447         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
448         if(asString === true){
449             return fs;
450         }
451         return Roo.urlDecode(fs);
452     },
453     
454     /**
455      * Returns the fields in this form as an object with key/value pairs. 
456      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
457      * @return {Object}
458      */
459     getFieldValues : function(with_hidden)
460     {
461         if (this.childForms) {
462             // copy values from the child forms
463             // should this call getFieldValues - probably not as we do not currently copy
464             // hidden fields when we generate..
465             Roo.each(this.childForms, function (f) {
466                 this.setValues(f.getValues());
467             }, this);
468         }
469         
470         var ret = {};
471         this.items.each(function(f){
472             if (!f.getName()) {
473                 return;
474             }
475             var v = f.getValue();
476             // not sure if this supported any more..
477             if ((typeof(v) == 'object') && f.getRawValue) {
478                 v = f.getRawValue() ; // dates..
479             }
480             // combo boxes where name != hiddenName...
481             if (f.name != f.getName()) {
482                 ret[f.name] = f.getRawValue();
483             }
484             ret[f.getName()] = v;
485         });
486         
487         return ret;
488     },
489
490     /**
491      * Clears all invalid messages in this form.
492      * @return {BasicForm} this
493      */
494     clearInvalid : function(){
495         this.items.each(function(f){
496            f.clearInvalid();
497         });
498         
499         Roo.each(this.childForms || [], function (f) {
500             f.clearInvalid();
501         });
502         
503         
504         return this;
505     },
506
507     /**
508      * Resets this form.
509      * @return {BasicForm} this
510      */
511     reset : function(){
512         this.items.each(function(f){
513             f.reset();
514         });
515         
516         Roo.each(this.childForms || [], function (f) {
517             f.reset();
518         });
519        
520         
521         return this;
522     },
523
524     /**
525      * Add Roo.form components to this form.
526      * @param {Field} field1
527      * @param {Field} field2 (optional)
528      * @param {Field} etc (optional)
529      * @return {BasicForm} this
530      */
531     add : function(){
532         this.items.addAll(Array.prototype.slice.call(arguments, 0));
533         return this;
534     },
535
536
537     /**
538      * Removes a field from the items collection (does NOT remove its markup).
539      * @param {Field} field
540      * @return {BasicForm} this
541      */
542     remove : function(field){
543         this.items.remove(field);
544         return this;
545     },
546
547     /**
548      * Looks at the fields in this form, checks them for an id attribute,
549      * and calls applyTo on the existing dom element with that id.
550      * @return {BasicForm} this
551      */
552     render : function(){
553         this.items.each(function(f){
554             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
555                 f.applyTo(f.id);
556             }
557         });
558         return this;
559     },
560
561     /**
562      * Calls {@link Ext#apply} for all fields in this form with the passed object.
563      * @param {Object} values
564      * @return {BasicForm} this
565      */
566     applyToFields : function(o){
567         this.items.each(function(f){
568            Roo.apply(f, o);
569         });
570         return this;
571     },
572
573     /**
574      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
575      * @param {Object} values
576      * @return {BasicForm} this
577      */
578     applyIfToFields : function(o){
579         this.items.each(function(f){
580            Roo.applyIf(f, o);
581         });
582         return this;
583     }
584 });
585
586 // back compat
587 Roo.BasicForm = Roo.form.BasicForm;