source: trunk/web/addons/job_monarch/lib/extjs-30/src/widgets/form/CheckboxGroup.js @ 625

Last change on this file since 625 was 625, checked in by ramonb, 15 years ago

lib/extjs-30:

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