3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.com/license
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>
13 var myCheckboxGroup = new Ext.form.CheckboxGroup({
15 xtype: 'checkboxgroup',
16 fieldLabel: 'Single Column',
17 itemCls: 'x-check-group-alt',
18 // Put all controls in a single column with width 100%
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'}
28 * Creates a new CheckboxGroup
29 * @param {Object} config Configuration options
30 * @xtype checkboxgroup
32 Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {
34 * @cfg {Array} items An Array of {@link Ext.form.Checkbox Checkbox}es or Checkbox config objects
35 * to arrange in the group.
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>
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.
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.
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")
67 blankText : "You must select at least one item in this group",
70 defaultType : 'checkbox',
73 groupCls : 'x-form-check-group',
76 initComponent: function(){
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.
86 this.on('change', this.validate, this);
87 Ext.form.CheckboxGroup.superclass.initComponent.call(this);
91 onRender : function(ct, position){
100 bufferResize: false // Default this to false, since it doesn't really have a proper ownerCt.
104 defaultType: this.defaultType,
112 if(this.items[0].items){
114 // The container has standard ColumnLayout configs, so pass them in directly
116 Ext.apply(panelCfg, {
117 layoutConfig: {columns: this.items.length},
118 defaults: this.defaults,
121 for(var i=0, len=this.items.length; i<len; i++){
122 Ext.applyIf(this.items[i], colCfg);
127 // The container has field item configs, so we have to generate the column
128 // panels first then move the items into the columns as needed.
130 var numCols, cols = [];
132 if(typeof this.columns == 'string'){ // 'auto' so create a col per item
133 this.columns = this.items.length;
135 if(!Ext.isArray(this.columns)){
137 for(var i=0; i<this.columns; i++){
138 cs.push((100/this.columns)*.01); // distribute by even %
143 numCols = this.columns.length;
145 // Generate the column configs with the correct width setting
146 for(var i=0; i<numCols; i++){
147 var cc = Ext.apply({items:[]}, colCfg);
148 cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];
150 cc.defaults = Ext.apply(cc.defaults || {}, this.defaults);
155 // Distribute the original items into the columns
157 var rows = Math.ceil(this.items.length / numCols), ri = 0;
158 for(var i=0, len=this.items.length; i<len; i++){
159 if(i>0 && i%rows==0){
162 if(this.items[i].fieldLabel){
163 this.items[i].hideLabel = false;
165 cols[ri].items.push(this.items[i]);
168 for(var i=0, len=this.items.length; i<len; i++){
169 var ci = i % numCols;
170 if(this.items[i].fieldLabel){
171 this.items[i].hideLabel = false;
173 cols[ci].items.push(this.items[i]);
177 Ext.apply(panelCfg, {
178 layoutConfig: {columns: numCols},
183 this.panel = new Ext.Container(panelCfg);
184 this.panel.ownerCt = this;
185 this.el = this.panel.getEl();
187 if(this.forId && this.itemCls){
188 var l = this.el.up(this.itemCls).child('label', true);
190 l.setAttribute('htmlFor', this.forId);
194 var fields = this.panel.findBy(function(c){
195 return c.isFormField;
198 this.items = new Ext.util.MixedCollection();
199 this.items.addAll(fields);
201 Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);
204 initValue : function(){
206 this.setValue.apply(this, this.buffered ? this.value : [this.value]);
207 delete this.buffered;
212 afterRender : function(){
213 Ext.form.CheckboxGroup.superclass.afterRender.call(this);
214 this.eachItem(function(item){
215 item.on('check', this.fireChecked, this);
221 doLayout: function(){
222 //ugly method required to layout hidden items
224 this.panel.forceLayout = this.ownerCt.forceLayout;
225 this.panel.doLayout();
230 fireChecked: function(){
232 this.eachItem(function(item){
237 this.fireEvent('change', this, arr);
241 * Runs CheckboxGroup's validations and returns an array of any errors. The only error by default
242 * is if allowBlank is set to true and no items are checked.
243 * @return {Array} Array of all validation errors
245 getErrors: function() {
246 var errors = Ext.form.CheckboxGroup.superclass.getErrors.apply(this, arguments);
248 if (!this.allowBlank) {
251 this.eachItem(function(f){
253 return (blank = false);
257 if (blank) errors.push(this.blankText);
265 //override the behaviour to check sub items.
266 if (this.disabled || !this.rendered) {
272 this.eachItem(function(item){
283 setReadOnly : function(readOnly){
285 this.eachItem(function(item){
286 item.setReadOnly(readOnly);
289 this.readOnly = readOnly;
293 onDisable : function(){
294 this.eachItem(function(item){
300 onEnable : function(){
301 this.eachItem(function(item){
307 onResize : function(w, h){
308 this.panel.setSize(w, h);
309 this.panel.doLayout();
312 // inherit docs from Field
314 if (this.originalValue) {
316 this.eachItem(function(c){
319 c.originalValue = c.getValue();
322 // Set items stored in originalValue, ugly - set a flag to reset the originalValue
323 // during the horrible onSetValue. This will allow trackResetOnLoad to function.
324 this.resetOriginal = true;
325 this.setValue(this.originalValue);
326 delete this.resetOriginal;
328 this.eachItem(function(c){
334 // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
335 // Important because reset is being called on both the group and the individual items.
342 * {@link Ext.form.Checkbox#setValue Set the value(s)} of an item or items
343 * in the group. Examples illustrating how this method may be called:
345 // call with name and value
346 myCheckboxGroup.setValue('cb-col-1', true);
347 // call with an array of boolean values
348 myCheckboxGroup.setValue([true, false, false]);
349 // call with an object literal specifying item:value pairs
350 myCheckboxGroup.setValue({
354 // use comma separated string to set items with name to true (checked)
355 myCheckboxGroup.setValue('cb-col-1,cb-col-3');
357 * See {@link Ext.form.Checkbox#setValue} for additional information.
358 * @param {Mixed} id The checkbox to check, or as described by example shown.
359 * @param {Boolean} value (optional) The value to set the item.
360 * @return {Ext.form.CheckboxGroup} this
362 setValue: function(){
364 this.onSetValue.apply(this, arguments);
366 this.buffered = true;
367 this.value = arguments;
374 * Sets the values of one or more of the items within the CheckboxGroup
375 * @param {String|Array|Object} id Can take multiple forms. Can be optionally:
377 * <li>An ID string to be used with a second argument</li>
378 * <li>An array of the form ['some', 'list', 'of', 'ids', 'to', 'mark', 'checked']</li>
379 * <li>An array in the form [true, true, false, true, false] etc, where each item relates to the check status of
380 * the checkbox at the same index</li>
381 * <li>An object containing ids of the checkboxes as keys and check values as properties</li>
383 * @param {String} value The value to set the field to if the first argument was a string
385 onSetValue: function(id, value){
386 if(arguments.length == 1){
388 Ext.each(id, function(val, idx){
389 if (Ext.isObject(val) && val.setValue){ // array of checkbox components to be checked
391 if (this.resetOriginal === true) {
392 val.originalValue = val.getValue();
394 } else { // an array of boolean values
395 var item = this.items.itemAt(idx);
401 }else if(Ext.isObject(id)){
402 // set of name/value pairs
404 var f = this.getBox(i);
410 this.setValueForItem(id);
413 var f = this.getBox(id);
421 beforeDestroy: function(){
422 Ext.destroy(this.panel);
423 if (!this.rendered) {
424 Ext.destroy(this.items);
426 Ext.form.CheckboxGroup.superclass.beforeDestroy.call(this);
430 setValueForItem : function(val){
431 val = String(val).split(',');
432 this.eachItem(function(item){
433 if(val.indexOf(item.inputValue)> -1){
440 getBox : function(id){
442 this.eachItem(function(f){
443 if(id == f || f.dataIndex == id || f.id == id || f.getName() == id){
452 * Gets an array of the selected {@link Ext.form.Checkbox} in the group.
453 * @return {Array} An array of the selected checkboxes.
455 getValue : function(){
457 this.eachItem(function(item){
467 * Convenience function which passes the given function to every item in the composite
468 * @param {Function} fn The function to call
469 * @param {Object} scope Optional scope object
471 eachItem: function(fn, scope) {
472 if(this.items && this.items.each){
473 this.items.each(fn, scope || this);
483 * @method getRawValue
486 getRawValue : Ext.emptyFn,
489 * @method setRawValue
492 setRawValue : Ext.emptyFn
496 Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);