Roo/form/Form.js
[roojs1] / Roo / form / Form.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.Form
14  * @extends Roo.form.BasicForm
15  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
16  * @constructor
17  * @param {Object} config Configuration options
18  */
19 Roo.form.Form = function(config){
20     var xitems =  [];
21     if (config.items) {
22         xitems = config.items;
23         delete config.items;
24     }
25     this.childForms = [];
26     
27     Roo.form.Form.superclass.constructor.call(this, null, config);
28     this.url = this.url || this.action;
29     if(!this.root){
30         this.root = new Roo.form.Layout(Roo.applyIf({
31             id: Roo.id()
32         }, config));
33     }
34     this.active = this.root;
35     /**
36      * Array of all the buttons that have been added to this form via {@link addButton}
37      * @type Array
38      */
39     this.buttons = [];
40     this.allItems = [];
41     this.addEvents({
42         /**
43          * @event clientvalidation
44          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
45          * @param {Form} this
46          * @param {Boolean} valid true if the form has passed client-side validation
47          */
48         clientvalidation: true,
49         /**
50          * @event rendered
51          * Fires when the form is rendered
52          * @param {Roo.form.Form} form
53          */
54         rendered : true
55     });
56     
57     Roo.each(xitems, this.addxtype, this);
58     
59     
60     
61 };
62
63 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
64     /**
65      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
66      */
67     /**
68      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
69      */
70     /**
71      * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
72      */
73     buttonAlign:'center',
74
75     /**
76      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
77      */
78     minButtonWidth:75,
79
80     /**
81      * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
82      * This property cascades to child containers if not set.
83      */
84     labelAlign:'left',
85
86     /**
87      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
88      * fires a looping event with that state. This is required to bind buttons to the valid
89      * state using the config value formBind:true on the button.
90      */
91     monitorValid : false,
92
93     /**
94      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
95      */
96     monitorPoll : 200,
97
98     /**
99      * childForms - used for multi-tab forms
100      * @type {Array}
101      */
102     
103     childForms : false,
104     /**
105      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
106      * fields are added and the column is closed. If no fields are passed the column remains open
107      * until end() is called.
108      * @param {Object} config The config to pass to the column
109      * @param {Field} field1 (optional)
110      * @param {Field} field2 (optional)
111      * @param {Field} etc (optional)
112      * @return Column The column container object
113      */
114     column : function(c){
115         var col = new Roo.form.Column(c);
116         this.start(col);
117         if(arguments.length > 1){ // duplicate code required because of Opera
118             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
119             this.end();
120         }
121         return col;
122     },
123
124     /**
125      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
126      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
127      * until end() is called.
128      * @param {Object} config The config to pass to the fieldset
129      * @param {Field} field1 (optional)
130      * @param {Field} field2 (optional)
131      * @param {Field} etc (optional)
132      * @return FieldSet The fieldset container object
133      */
134     fieldset : function(c){
135         var fs = new Roo.form.FieldSet(c);
136         this.start(fs);
137         if(arguments.length > 1){ // duplicate code required because of Opera
138             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
139             this.end();
140         }
141         return fs;
142     },
143
144     /**
145      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
146      * fields are added and the container is closed. If no fields are passed the container remains open
147      * until end() is called.
148      * @param {Object} config The config to pass to the Layout
149      * @param {Field} field1 (optional)
150      * @param {Field} field2 (optional)
151      * @param {Field} etc (optional)
152      * @return Layout The container object
153      */
154     container : function(c){
155         var l = new Roo.form.Layout(c);
156         this.start(l);
157         if(arguments.length > 1){ // duplicate code required because of Opera
158             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
159             this.end();
160         }
161         return l;
162     },
163
164     /**
165      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
166      * @param {Object} container A Roo.form.Layout or subclass of Layout
167      * @return {Form} this
168      */
169     start : function(c){
170         // cascade label info
171         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
172         this.active.stack.push(c);
173         c.ownerCt = this.active;
174         this.active = c;
175         return this;
176     },
177
178     /**
179      * Closes the current open container
180      * @return {Form} this
181      */
182     end : function(){
183         if(this.active == this.root){
184             return this;
185         }
186         this.active = this.active.ownerCt;
187         return this;
188     },
189
190     /**
191      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
192      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
193      * as the label of the field.
194      * @param {Field} field1
195      * @param {Field} field2 (optional)
196      * @param {Field} etc. (optional)
197      * @return {Form} this
198      */
199     add : function(){
200         this.active.stack.push.apply(this.active.stack, arguments);
201         this.allItems.push.apply(this.allItems,arguments);
202         var r = [];
203         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
204             if(a[i].isFormField){
205                 r.push(a[i]);
206             }
207         }
208         if(r.length > 0){
209             Roo.form.Form.superclass.add.apply(this, r);
210         }
211         return this;
212     },
213     
214     /**
215      * Add a secondary form to this one, 
216      * Used to provide tabbed forms. One form is primary, with hidden values 
217      * which mirror the elements from the other forms.
218      * 
219      * @param {Roo.form.Form} form to add.
220      * 
221      */
222     
223     
224     addForm : function(form){
225        
226         this.childForms.push(form);
227         form.allItems.each(function (fe) {
228             
229             if (this.findField(fe.name)) { // already added..
230                 return;
231             }
232             this.add( new Roo.form.Hidden({
233                 name : fe.name
234             }));
235         }, this);
236         
237     },
238     
239     
240     
241      /**
242      * Find any element that has been added to a form, using it's ID or name
243      * This can include framesets, columns etc. along with regular fields..
244      * @param {String} id - id or name to find.
245      
246      * @return {Element} e - or false if nothing found.
247      */
248     findbyId : function(id)
249     {
250         var ret = false;
251         if (!id) {
252             return ret;
253         }
254         Ext.each(this.allItems, function(f){
255             if (f.id == id || f.name == id ){
256                 ret = f;
257                 return false;
258             }
259         });
260         return ret;
261     },
262
263     
264     
265     /**
266      * Render this form into the passed container. This should only be called once!
267      * @param {String/HTMLElement/Element} container The element this component should be rendered into
268      * @return {Form} this
269      */
270     render : function(ct){
271         ct = Roo.get(ct);
272         var o = this.autoCreate || {
273             tag: 'form',
274             method : this.method || 'POST',
275             id : this.id || Roo.id()
276         };
277         this.initEl(ct.createChild(o));
278
279         this.root.render(this.el);
280
281         this.items.each(function(f){
282             f.render('x-form-el-'+f.id);
283         });
284
285         if(this.buttons.length > 0){
286             // tables are required to maintain order and for correct IE layout
287             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
288                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
289                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
290             }}, null, true);
291             var tr = tb.getElementsByTagName('tr')[0];
292             for(var i = 0, len = this.buttons.length; i < len; i++) {
293                 var b = this.buttons[i];
294                 var td = document.createElement('td');
295                 td.className = 'x-form-btn-td';
296                 b.render(tr.appendChild(td));
297             }
298         }
299         if(this.monitorValid){ // initialize after render
300             this.startMonitoring();
301         }
302         this.fireEvent('rendered', this);
303         return this;
304     },
305
306     /**
307      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
308      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
309      * object or a valid Roo.DomHelper element config
310      * @param {Function} handler The function called when the button is clicked
311      * @param {Object} scope (optional) The scope of the handler function
312      * @return {Roo.Button}
313      */
314     addButton : function(config, handler, scope){
315         var bc = {
316             handler: handler,
317             scope: scope,
318             minWidth: this.minButtonWidth,
319             hideParent:true
320         };
321         if(typeof config == "string"){
322             bc.text = config;
323         }else{
324             Roo.apply(bc, config);
325         }
326         var btn = new Roo.Button(null, bc);
327         this.buttons.push(btn);
328         return btn;
329     },
330
331      /**
332      * Adds a series of form elements (using the xtype property as the factory method.
333      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
334      * @param {Object} config 
335      */
336     
337     addxtype : function()
338     {
339         var ar = Array.prototype.slice.call(arguments, 0);
340         var ret = false;
341         for(var i = 0; i < ar.length; i++) {
342             if (!ar[i]) {
343                 continue; // skip -- if this happends something invalid got sent, we 
344                 // should ignore it, as basically that interface element will not show up
345                 // and that should be pretty obvious!!
346             }
347             
348             if (Roo.form[ar[i].xtype]) {
349                 ar[i].form = this;
350                 var fe = Roo.factory(ar[i], Roo.form);
351                 if (!ret) {
352                     ret = fe;
353                 }
354                 fe.form = this;
355                 if (fe.store) {
356                     fe.store.form = this;
357                 }
358                 if (fe.isLayout) {  
359                          
360                     this.start(fe);
361                     this.allItems.push(fe);
362                     if (fe.items && fe.addxtype) {
363                         fe.addxtype.apply(fe, fe.items);
364                         delete fe.items;
365                     }
366                      this.end();
367                     continue;
368                 }
369                 
370                 
371                  
372                 this.add(fe);
373               //  console.log('adding ' + ar[i].xtype);
374             }
375             if (ar[i].xtype == 'Button') {  
376                 //console.log('adding button');
377                 //console.log(ar[i]);
378                 this.addButton(ar[i]);
379                 this.allItems.push(fe);
380                 continue;
381             }
382             
383             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
384                 alert('end is not supported on xtype any more, use items');
385             //    this.end();
386             //    //console.log('adding end');
387             }
388             
389         }
390         return ret;
391     },
392     
393     /**
394      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
395      * option "monitorValid"
396      */
397     startMonitoring : function(){
398         if(!this.bound){
399             this.bound = true;
400             Roo.TaskMgr.start({
401                 run : this.bindHandler,
402                 interval : this.monitorPoll || 200,
403                 scope: this
404             });
405         }
406     },
407
408     /**
409      * Stops monitoring of the valid state of this form
410      */
411     stopMonitoring : function(){
412         this.bound = false;
413     },
414
415     // private
416     bindHandler : function(){
417         if(!this.bound){
418             return false; // stops binding
419         }
420         var valid = true;
421         this.items.each(function(f){
422             if(!f.isValid(true)){
423                 valid = false;
424                 return false;
425             }
426         });
427         for(var i = 0, len = this.buttons.length; i < len; i++){
428             var btn = this.buttons[i];
429             if(btn.formBind === true && btn.disabled === valid){
430                 btn.setDisabled(!valid);
431             }
432         }
433         this.fireEvent('clientvalidation', this, valid);
434     }
435     
436     
437     
438     
439     
440     
441     
442     
443 });
444
445
446 // back compat
447 Roo.Form = Roo.form.Form;