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     /**
100      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
101      * fields are added and the column is closed. If no fields are passed the column remains open
102      * until end() is called.
103      * @param {Object} config The config to pass to the column
104      * @param {Field} field1 (optional)
105      * @param {Field} field2 (optional)
106      * @param {Field} etc (optional)
107      * @return Column The column container object
108      */
109     column : function(c){
110         var col = new Roo.form.Column(c);
111         this.start(col);
112         if(arguments.length > 1){ // duplicate code required because of Opera
113             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
114             this.end();
115         }
116         return col;
117     },
118
119     /**
120      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
121      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
122      * until end() is called.
123      * @param {Object} config The config to pass to the fieldset
124      * @param {Field} field1 (optional)
125      * @param {Field} field2 (optional)
126      * @param {Field} etc (optional)
127      * @return FieldSet The fieldset container object
128      */
129     fieldset : function(c){
130         var fs = new Roo.form.FieldSet(c);
131         this.start(fs);
132         if(arguments.length > 1){ // duplicate code required because of Opera
133             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
134             this.end();
135         }
136         return fs;
137     },
138
139     /**
140      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
141      * fields are added and the container is closed. If no fields are passed the container remains open
142      * until end() is called.
143      * @param {Object} config The config to pass to the Layout
144      * @param {Field} field1 (optional)
145      * @param {Field} field2 (optional)
146      * @param {Field} etc (optional)
147      * @return Layout The container object
148      */
149     container : function(c){
150         var l = new Roo.form.Layout(c);
151         this.start(l);
152         if(arguments.length > 1){ // duplicate code required because of Opera
153             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
154             this.end();
155         }
156         return l;
157     },
158
159     /**
160      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
161      * @param {Object} container A Roo.form.Layout or subclass of Layout
162      * @return {Form} this
163      */
164     start : function(c){
165         // cascade label info
166         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
167         this.active.stack.push(c);
168         c.ownerCt = this.active;
169         this.active = c;
170         return this;
171     },
172
173     /**
174      * Closes the current open container
175      * @return {Form} this
176      */
177     end : function(){
178         if(this.active == this.root){
179             return this;
180         }
181         this.active = this.active.ownerCt;
182         return this;
183     },
184
185     /**
186      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
187      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
188      * as the label of the field.
189      * @param {Field} field1
190      * @param {Field} field2 (optional)
191      * @param {Field} etc. (optional)
192      * @return {Form} this
193      */
194     add : function(){
195         this.active.stack.push.apply(this.active.stack, arguments);
196         this.allItems.push.apply(this.allItems,arguments);
197         var r = [];
198         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
199             if(a[i].isFormField){
200                 r.push(a[i]);
201             }
202         }
203         if(r.length > 0){
204             Roo.form.Form.superclass.add.apply(this, r);
205         }
206         return this;
207     },
208     
209
210     
211     
212     
213      /**
214      * Find any element that has been added to a form, using it's ID or name
215      * This can include framesets, columns etc. along with regular fields..
216      * @param {String} id - id or name to find.
217      
218      * @return {Element} e - or false if nothing found.
219      */
220     findbyId : function(id)
221     {
222         var ret = false;
223         if (!id) {
224             return ret;
225         }
226         Ext.each(this.allItems, function(f){
227             if (f.id == id || f.name == id ){
228                 ret = f;
229                 return false;
230             }
231         });
232         return ret;
233     },
234
235     
236     
237     /**
238      * Render this form into the passed container. This should only be called once!
239      * @param {String/HTMLElement/Element} container The element this component should be rendered into
240      * @return {Form} this
241      */
242     render : function(ct){
243         ct = Roo.get(ct);
244         var o = this.autoCreate || {
245             tag: 'form',
246             method : this.method || 'POST',
247             id : this.id || Roo.id()
248         };
249         this.initEl(ct.createChild(o));
250
251         this.root.render(this.el);
252
253         this.items.each(function(f){
254             f.render('x-form-el-'+f.id);
255         });
256
257         if(this.buttons.length > 0){
258             // tables are required to maintain order and for correct IE layout
259             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
260                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
261                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
262             }}, null, true);
263             var tr = tb.getElementsByTagName('tr')[0];
264             for(var i = 0, len = this.buttons.length; i < len; i++) {
265                 var b = this.buttons[i];
266                 var td = document.createElement('td');
267                 td.className = 'x-form-btn-td';
268                 b.render(tr.appendChild(td));
269             }
270         }
271         if(this.monitorValid){ // initialize after render
272             this.startMonitoring();
273         }
274         this.fireEvent('rendered', this);
275         return this;
276     },
277
278     /**
279      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
280      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
281      * object or a valid Roo.DomHelper element config
282      * @param {Function} handler The function called when the button is clicked
283      * @param {Object} scope (optional) The scope of the handler function
284      * @return {Roo.Button}
285      */
286     addButton : function(config, handler, scope){
287         var bc = {
288             handler: handler,
289             scope: scope,
290             minWidth: this.minButtonWidth,
291             hideParent:true
292         };
293         if(typeof config == "string"){
294             bc.text = config;
295         }else{
296             Roo.apply(bc, config);
297         }
298         var btn = new Roo.Button(null, bc);
299         this.buttons.push(btn);
300         return btn;
301     },
302
303      /**
304      * Adds a series of form elements (using the xtype property as the factory method.
305      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
306      * @param {Object} config 
307      */
308     
309     addxtype : function()
310     {
311         var ar = Array.prototype.slice.call(arguments, 0);
312         var ret = false;
313         for(var i = 0; i < ar.length; i++) {
314             if (!ar[i]) {
315                 continue; // skip -- if this happends something invalid got sent, we 
316                 // should ignore it, as basically that interface element will not show up
317                 // and that should be pretty obvious!!
318             }
319             
320             if (Roo.form[ar[i].xtype]) {
321                 ar[i].form = this;
322                 var fe = Roo.factory(ar[i], Roo.form);
323                 if (!ret) {
324                     ret = fe;
325                 }
326                 fe.form = this;
327                 if (fe.store) {
328                     fe.store.form = this;
329                 }
330                 if (fe.isLayout) {  
331                          
332                     this.start(fe);
333                     this.allItems.push(fe);
334                     if (fe.items && fe.addxtype) {
335                         fe.addxtype.apply(fe, fe.items);
336                         delete fe.items;
337                     }
338                      this.end();
339                     continue;
340                 }
341                 
342                 
343                  
344                 this.add(fe);
345               //  console.log('adding ' + ar[i].xtype);
346             }
347             if (ar[i].xtype == 'Button') {  
348                 //console.log('adding button');
349                 //console.log(ar[i]);
350                 this.addButton(ar[i]);
351                 this.allItems.push(fe);
352                 continue;
353             }
354             
355             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
356                 alert('end is not supported on xtype any more, use items');
357             //    this.end();
358             //    //console.log('adding end');
359             }
360             
361         }
362         return ret;
363     },
364     
365     /**
366      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
367      * option "monitorValid"
368      */
369     startMonitoring : function(){
370         if(!this.bound){
371             this.bound = true;
372             Roo.TaskMgr.start({
373                 run : this.bindHandler,
374                 interval : this.monitorPoll || 200,
375                 scope: this
376             });
377         }
378     },
379
380     /**
381      * Stops monitoring of the valid state of this form
382      */
383     stopMonitoring : function(){
384         this.bound = false;
385     },
386
387     // private
388     bindHandler : function(){
389         if(!this.bound){
390             return false; // stops binding
391         }
392         var valid = true;
393         this.items.each(function(f){
394             if(!f.isValid(true)){
395                 valid = false;
396                 return false;
397             }
398         });
399         for(var i = 0, len = this.buttons.length; i < len; i++){
400             var btn = this.buttons[i];
401             if(btn.formBind === true && btn.disabled === valid){
402                 btn.setDisabled(!valid);
403             }
404         }
405         this.fireEvent('clientvalidation', this, valid);
406     }
407     
408     
409     
410     
411     
412     
413     
414     
415 });
416
417
418 // back compat
419 Roo.Form = Roo.form.Form;