Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / widgets / form / CheckboxGroup.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.form.CheckboxGroup\r
9  * @extends Ext.form.Field\r
10  * <p>A grouping container for {@link Ext.form.Checkbox} controls.</p>\r
11  * <p>Sample usage:</p>\r
12  * <pre><code>\r
13 var myCheckboxGroup = new Ext.form.CheckboxGroup({\r
14     id:'myGroup',\r
15     xtype: 'checkboxgroup',\r
16     fieldLabel: 'Single Column',\r
17     itemCls: 'x-check-group-alt',\r
18     // Put all controls in a single column with width 100%\r
19     columns: 1,\r
20     items: [\r
21         {boxLabel: 'Item 1', name: 'cb-col-1'},\r
22         {boxLabel: 'Item 2', name: 'cb-col-2', checked: true},\r
23         {boxLabel: 'Item 3', name: 'cb-col-3'}\r
24     ]\r
25 });\r
26  * </code></pre>\r
27  * @constructor\r
28  * Creates a new CheckboxGroup\r
29  * @param {Object} config Configuration options\r
30  * @xtype checkboxgroup\r
31  */\r
32 Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {\r
33     /**\r
34      * @cfg {Array} items An Array of {@link Ext.form.Checkbox Checkbox}es or Checkbox config objects\r
35      * to arrange in the group.\r
36      */\r
37     /**\r
38      * @cfg {String/Number/Array} columns Specifies the number of columns to use when displaying grouped\r
39      * checkbox/radio controls using automatic layout.  This config can take several types of values:\r
40      * <ul><li><b>'auto'</b> : <p class="sub-desc">The controls will be rendered one per column on one row and the width\r
41      * of each column will be evenly distributed based on the width of the overall field container. This is the default.</p></li>\r
42      * <li><b>Number</b> : <p class="sub-desc">If you specific a number (e.g., 3) that number of columns will be \r
43      * created and the contained controls will be automatically distributed based on the value of {@link #vertical}.</p></li>\r
44      * <li><b>Array</b> : Object<p class="sub-desc">You can also specify an array of column widths, mixing integer\r
45      * (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will\r
46      * be rendered first, then any float values will be calculated as a percentage of the remaining space. Float\r
47      * values do not have to add up to 1 (100%) although if you want the controls to take up the entire field\r
48      * container you should do so.</p></li></ul>\r
49      */\r
50     columns : 'auto',\r
51     /**\r
52      * @cfg {Boolean} vertical True to distribute contained controls across columns, completely filling each column \r
53      * top to bottom before starting on the next column.  The number of controls in each column will be automatically\r
54      * calculated to keep columns as even as possible.  The default value is false, so that controls will be added\r
55      * to columns one at a time, completely filling each row left to right before starting on the next row.\r
56      */\r
57     vertical : false,\r
58     /**\r
59      * @cfg {Boolean} allowBlank False to validate that at least one item in the group is checked (defaults to true).\r
60      * If no items are selected at validation time, {@link @blankText} will be used as the error text.\r
61      */\r
62     allowBlank : true,\r
63     /**\r
64      * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails (defaults to "You must \r
65      * select at least one item in this group")\r
66      */\r
67     blankText : "You must select at least one item in this group",\r
68     \r
69     // private\r
70     defaultType : 'checkbox',\r
71     \r
72     // private\r
73     groupCls : 'x-form-check-group',\r
74     \r
75     // private\r
76     initComponent: function(){\r
77         this.addEvents(\r
78             /**\r
79              * @event change\r
80              * Fires when the state of a child checkbox changes.\r
81              * @param {Ext.form.CheckboxGroup} this\r
82              * @param {Array} checked An array containing the checked boxes.\r
83              */\r
84             'change'\r
85         );   \r
86         Ext.form.CheckboxGroup.superclass.initComponent.call(this);\r
87     },\r
88     \r
89     // private\r
90     onRender : function(ct, position){\r
91         if(!this.el){\r
92             var panelCfg = {\r
93                 id: this.id,\r
94                 cls: this.groupCls,\r
95                 layout: 'column',\r
96                 border: false,\r
97                 renderTo: ct,\r
98                 bufferResize: false // Default this to false, since it doesn't really have a proper ownerCt.\r
99             };\r
100             var colCfg = {\r
101                 defaultType: this.defaultType,\r
102                 layout: 'form',\r
103                 border: false,\r
104                 defaults: {\r
105                     hideLabel: true,\r
106                     anchor: '100%'\r
107                 }\r
108             };\r
109             \r
110             if(this.items[0].items){\r
111                 \r
112                 // The container has standard ColumnLayout configs, so pass them in directly\r
113                 \r
114                 Ext.apply(panelCfg, {\r
115                     layoutConfig: {columns: this.items.length},\r
116                     defaults: this.defaults,\r
117                     items: this.items\r
118                 });\r
119                 for(var i=0, len=this.items.length; i<len; i++){\r
120                     Ext.applyIf(this.items[i], colCfg);\r
121                 }\r
122                 \r
123             }else{\r
124                 \r
125                 // The container has field item configs, so we have to generate the column\r
126                 // panels first then move the items into the columns as needed.\r
127                 \r
128                 var numCols, cols = [];\r
129                 \r
130                 if(typeof this.columns == 'string'){ // 'auto' so create a col per item\r
131                     this.columns = this.items.length;\r
132                 }\r
133                 if(!Ext.isArray(this.columns)){\r
134                     var cs = [];\r
135                     for(var i=0; i<this.columns; i++){\r
136                         cs.push((100/this.columns)*.01); // distribute by even %\r
137                     }\r
138                     this.columns = cs;\r
139                 }\r
140                 \r
141                 numCols = this.columns.length;\r
142                 \r
143                 // Generate the column configs with the correct width setting\r
144                 for(var i=0; i<numCols; i++){\r
145                     var cc = Ext.apply({items:[]}, colCfg);\r
146                     cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];\r
147                     if(this.defaults){\r
148                         cc.defaults = Ext.apply(cc.defaults || {}, this.defaults)\r
149                     }\r
150                     cols.push(cc);\r
151                 };\r
152                 \r
153                 // Distribute the original items into the columns\r
154                 if(this.vertical){\r
155                     var rows = Math.ceil(this.items.length / numCols), ri = 0;\r
156                     for(var i=0, len=this.items.length; i<len; i++){\r
157                         if(i>0 && i%rows==0){\r
158                             ri++;\r
159                         }\r
160                         if(this.items[i].fieldLabel){\r
161                             this.items[i].hideLabel = false;\r
162                         }\r
163                         cols[ri].items.push(this.items[i]);\r
164                     };\r
165                 }else{\r
166                     for(var i=0, len=this.items.length; i<len; i++){\r
167                         var ci = i % numCols;\r
168                         if(this.items[i].fieldLabel){\r
169                             this.items[i].hideLabel = false;\r
170                         }\r
171                         cols[ci].items.push(this.items[i]);\r
172                     };\r
173                 }\r
174                 \r
175                 Ext.apply(panelCfg, {\r
176                     layoutConfig: {columns: numCols},\r
177                     items: cols\r
178                 });\r
179             }\r
180             \r
181             this.panel = new Ext.Panel(panelCfg);\r
182             this.panel.ownerCt = this;\r
183             this.el = this.panel.getEl();\r
184             \r
185             if(this.forId && this.itemCls){\r
186                 var l = this.el.up(this.itemCls).child('label', true);\r
187                 if(l){\r
188                     l.setAttribute('htmlFor', this.forId);\r
189                 }\r
190             }\r
191             \r
192             var fields = this.panel.findBy(function(c){\r
193                 return c.isFormField;\r
194             }, this);\r
195             \r
196             this.items = new Ext.util.MixedCollection();\r
197             this.items.addAll(fields);\r
198         }\r
199         Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);\r
200     },\r
201     \r
202     initValue : function(){\r
203         if(this.value){\r
204             this.setValue.apply(this, this.buffered ? this.value : [this.value]);\r
205             delete this.buffered;\r
206             delete this.value;\r
207         }\r
208     },\r
209     \r
210     afterRender : function(){\r
211         Ext.form.CheckboxGroup.superclass.afterRender.call(this);\r
212         this.eachItem(function(item){\r
213             item.on('check', this.fireChecked, this);\r
214             item.inGroup = true;\r
215         });\r
216     },\r
217     \r
218     // private\r
219     doLayout: function(){\r
220         //ugly method required to layout hidden items\r
221         if(this.rendered){\r
222             this.panel.forceLayout = this.ownerCt.forceLayout;\r
223             this.panel.doLayout();\r
224         }\r
225     },\r
226     \r
227     // private\r
228     fireChecked: function(){\r
229         var arr = [];\r
230         this.eachItem(function(item){\r
231             if(item.checked){\r
232                 arr.push(item);\r
233             }\r
234         });\r
235         this.fireEvent('change', this, arr);\r
236     },\r
237     \r
238     // private\r
239     validateValue : function(value){\r
240         if(!this.allowBlank){\r
241             var blank = true;\r
242             this.eachItem(function(f){\r
243                 if(f.checked){\r
244                     return (blank = false);\r
245                 }\r
246             });\r
247             if(blank){\r
248                 this.markInvalid(this.blankText);\r
249                 return false;\r
250             }\r
251         }\r
252         return true;\r
253     },\r
254     \r
255     // private\r
256     isDirty: function(){\r
257         //override the behaviour to check sub items.\r
258         if (this.disabled || !this.rendered) {\r
259             return false;\r
260         }\r
261 \r
262         var dirty = false;\r
263         this.eachItem(function(item){\r
264             if(item.isDirty()){\r
265                 dirty = true;\r
266                 return false;\r
267             }\r
268         });\r
269         return dirty;\r
270     },\r
271     \r
272     // private\r
273     onDisable : function(){\r
274         this.eachItem(function(item){\r
275             item.disable();\r
276         });\r
277     },\r
278 \r
279     // private\r
280     onEnable : function(){\r
281         this.eachItem(function(item){\r
282             item.enable();\r
283         });\r
284     },\r
285     \r
286     // private\r
287     doLayout: function(){\r
288         if(this.rendered){\r
289             this.panel.forceLayout = this.ownerCt.forceLayout;\r
290             this.panel.doLayout();\r
291         }\r
292     },\r
293     \r
294     // private\r
295     onResize : function(w, h){\r
296         this.panel.setSize(w, h);\r
297         this.panel.doLayout();\r
298     },\r
299     \r
300     // inherit docs from Field\r
301     reset : function(){\r
302         Ext.form.CheckboxGroup.superclass.reset.call(this);\r
303         this.eachItem(function(c){\r
304             if(c.reset){\r
305                 c.reset();\r
306             }\r
307         });\r
308     },\r
309     \r
310     /**\r
311      * {@link Ext.form.Checkbox#setValue Set the value(s)} of an item or items\r
312      * in the group. Examples illustrating how this method may be called:\r
313      * <pre><code>\r
314 // call with name and value\r
315 myCheckboxGroup.setValue('cb-col-1', true);\r
316 // call with an array of boolean values \r
317 myCheckboxGroup.setValue([true, false, false]);\r
318 // call with an object literal specifying item:value pairs\r
319 myCheckboxGroup.setValue({\r
320     'cb-col-2': false,\r
321     'cb-col-3': true\r
322 });\r
323 // use comma separated string to set items with name to true (checked)\r
324 myCheckboxGroup.setValue('cb-col-1,cb-col-3');\r
325      * </code></pre>\r
326      * See {@link Ext.form.Checkbox#setValue} for additional information.\r
327      * @param {Mixed} id The checkbox to check, or as described by example shown.\r
328      * @param {Boolean} value (optional) The value to set the item.\r
329      * @return {Ext.form.CheckboxGroup} this\r
330      */\r
331     setValue: function(){\r
332         if(this.rendered){\r
333             this.onSetValue.apply(this, arguments);\r
334         }else{\r
335             this.buffered = true;\r
336             this.value = arguments;\r
337         }\r
338         return this;\r
339     },\r
340     \r
341     onSetValue: function(id, value){\r
342         if(arguments.length == 1){\r
343             if(Ext.isArray(id)){\r
344                 // an array of boolean values\r
345                 Ext.each(id, function(val, idx){\r
346                     var item = this.items.itemAt(idx);\r
347                     if(item){\r
348                         item.setValue(val);\r
349                     }\r
350                 }, this);\r
351             }else if(Ext.isObject(id)){\r
352                 // set of name/value pairs\r
353                 for(var i in id){\r
354                     var f = this.getBox(i);\r
355                     if(f){\r
356                         f.setValue(id[i]);\r
357                     }\r
358                 }\r
359             }else{\r
360                 this.setValueForItem(id);\r
361             }\r
362         }else{\r
363             var f = this.getBox(id);\r
364             if(f){\r
365                 f.setValue(value);\r
366             }\r
367         }\r
368     },\r
369     \r
370     // private\r
371     onDestroy: function(){\r
372         Ext.destroy(this.panel);\r
373         Ext.form.CheckboxGroup.superclass.onDestroy.call(this);\r
374 \r
375     },\r
376     \r
377     setValueForItem : function(val){\r
378         val = String(val).split(',');\r
379         this.eachItem(function(item){\r
380             if(val.indexOf(item.inputValue)> -1){\r
381                 item.setValue(true);\r
382             }\r
383         });\r
384     },\r
385     \r
386     // private\r
387     getBox : function(id){\r
388         var box = null;\r
389         this.eachItem(function(f){\r
390             if(id == f || f.dataIndex == id || f.id == id || f.getName() == id){\r
391                 box = f;\r
392                 return false;\r
393             }\r
394         });\r
395         return box;\r
396     },\r
397     \r
398     /**\r
399      * Gets an array of the selected {@link Ext.form.Checkbox} in the group.\r
400      * @return {Array} An array of the selected checkboxes.\r
401      */\r
402     getValue : function(){\r
403         var out = [];\r
404         this.eachItem(function(item){\r
405             if(item.checked){\r
406                 out.push(item);\r
407             }\r
408         });\r
409         return out;\r
410     },\r
411     \r
412     // private\r
413     eachItem: function(fn){\r
414         if(this.items && this.items.each){\r
415             this.items.each(fn, this);\r
416         }\r
417     },\r
418     \r
419     /**\r
420      * @cfg {String} name\r
421      * @hide\r
422      */\r
423 \r
424     /**\r
425      * @method getRawValue\r
426      * @hide\r
427      */\r
428     getRawValue : Ext.emptyFn,\r
429     \r
430     /**\r
431      * @method setRawValue\r
432      * @hide\r
433      */\r
434     setRawValue : Ext.emptyFn\r
435     \r
436 });\r
437 \r
438 Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);\r