Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / docs / source / CheckboxGroup.html
1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-form.CheckboxGroup-method-constructor'><span id='Ext-form.CheckboxGroup'>/**
2 </span></span> * @class Ext.form.CheckboxGroup
3  * @extends Ext.form.FieldContainer
4  * &lt;p&gt;A {@link Ext.form.FieldContainer field container} which has a specialized layout for arranging
5  * {@link Ext.form.field.Checkbox} controls into columns, and provides convenience {@link Ext.form.field.Field} methods
6  * for {@link #getValue getting}, {@link #setValue setting}, and {@link #validate validating} the group
7  * of checkboxes as a whole.&lt;/p&gt;
8  * &lt;p&gt;&lt;b&gt;Validation:&lt;/b&gt; Individual checkbox fields themselves have no default validation behavior, but
9  * sometimes you want to require a user to select at least one of a group of checkboxes. CheckboxGroup
10  * allows this by setting the config &lt;tt&gt;{@link #allowBlank}:false&lt;/tt&gt;; when the user does not check at
11  * least one of the checkboxes, the entire group will be highlighted as invalid and the
12  * {@link #blankText error message} will be displayed according to the {@link #msgTarget} config.&lt;/p&gt;
13  * &lt;p&gt;&lt;b&gt;Layout:&lt;/b&gt; The default layout for CheckboxGroup makes it easy to arrange the checkboxes into
14  * columns; see the {@link #columns} and {@link #vertical} config documentation for details. You may also
15  * use a completely different layout by setting the {@link #layout} to one of the other supported layout
16  * types; for instance you may wish to use a custom arrangement of hbox and vbox containers. In that case
17  * the checkbox components at any depth will still be managed by the CheckboxGroup's validation.&lt;/p&gt;
18  * {@img Ext.form.RadioGroup/Ext.form.RadioGroup.png Ext.form.RadioGroup component}
19  * &lt;p&gt;Example usage:&lt;/p&gt;
20  * &lt;pre&gt;&lt;code&gt;
21 Ext.create('Ext.form.Panel', {
22     title: 'RadioGroup Example',
23     width: 300,
24     height: 125,
25     bodyPadding: 10,
26     renderTo: Ext.getBody(),        
27     items:[{            
28         xtype: 'radiogroup',
29         fieldLabel: 'Two Columns',
30         // Arrange radio buttons into two columns, distributed vertically
31         columns: 2,
32         vertical: true,
33         items: [
34             {boxLabel: 'Item 1', name: 'rb', inputValue: '1'},
35             {boxLabel: 'Item 2', name: 'rb', inputValue: '2', checked: true},
36             {boxLabel: 'Item 3', name: 'rb', inputValue: '3'},
37             {boxLabel: 'Item 4', name: 'rb', inputValue: '4'},
38             {boxLabel: 'Item 5', name: 'rb', inputValue: '5'},
39             {boxLabel: 'Item 6', name: 'rb', inputValue: '6'}
40         ]
41     }]
42 });
43  * &lt;/code&gt;&lt;/pre&gt;
44  * @constructor
45  * Creates a new CheckboxGroup
46  * @param {Object} config Configuration options
47  * @xtype checkboxgroup
48  */
49 Ext.define('Ext.form.CheckboxGroup', {
50     extend:'Ext.form.FieldContainer',
51     mixins: {
52         field: 'Ext.form.field.Field'
53     },
54     alias: 'widget.checkboxgroup',
55     requires: ['Ext.layout.container.CheckboxGroup', 'Ext.form.field.Base'],
56
57 <span id='Ext-form.CheckboxGroup-cfg-name'>    /**
58 </span>     * @cfg {String} name
59      * @hide
60      */
61
62 <span id='Ext-form.CheckboxGroup-cfg-items'>    /**
63 </span>     * @cfg {Array} items An Array of {@link Ext.form.field.Checkbox Checkbox}es or Checkbox config objects
64      * to arrange in the group.
65      */
66
67 <span id='Ext-form.CheckboxGroup-cfg-columns'>    /**
68 </span>     * @cfg {String/Number/Array} columns Specifies the number of columns to use when displaying grouped
69      * checkbox/radio controls using automatic layout.  This config can take several types of values:
70      * &lt;ul&gt;&lt;li&gt;&lt;b&gt;'auto'&lt;/b&gt; : &lt;p class=&quot;sub-desc&quot;&gt;The controls will be rendered one per column on one row and the width
71      * of each column will be evenly distributed based on the width of the overall field container. This is the default.&lt;/p&gt;&lt;/li&gt;
72      * &lt;li&gt;&lt;b&gt;Number&lt;/b&gt; : &lt;p class=&quot;sub-desc&quot;&gt;If you specific a number (e.g., 3) that number of columns will be
73      * created and the contained controls will be automatically distributed based on the value of {@link #vertical}.&lt;/p&gt;&lt;/li&gt;
74      * &lt;li&gt;&lt;b&gt;Array&lt;/b&gt; : &lt;p class=&quot;sub-desc&quot;&gt;You can also specify an array of column widths, mixing integer
75      * (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will
76      * be rendered first, then any float values will be calculated as a percentage of the remaining space. Float
77      * values do not have to add up to 1 (100%) although if you want the controls to take up the entire field
78      * container you should do so.&lt;/p&gt;&lt;/li&gt;&lt;/ul&gt;
79      */
80     columns : 'auto',
81
82 <span id='Ext-form.CheckboxGroup-cfg-vertical'>    /**
83 </span>     * @cfg {Boolean} vertical True to distribute contained controls across columns, completely filling each column
84      * top to bottom before starting on the next column.  The number of controls in each column will be automatically
85      * calculated to keep columns as even as possible.  The default value is false, so that controls will be added
86      * to columns one at a time, completely filling each row left to right before starting on the next row.
87      */
88     vertical : false,
89
90 <span id='Ext-form.CheckboxGroup-cfg-allowBlank'>    /**
91 </span>     * @cfg {Boolean} allowBlank False to validate that at least one item in the group is checked (defaults to true).
92      * If no items are selected at validation time, {@link #blankText} will be used as the error text.
93      */
94     allowBlank : true,
95
96 <span id='Ext-form.CheckboxGroup-cfg-blankText'>    /**
97 </span>     * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails (defaults to &quot;You must
98      * select at least one item in this group&quot;)
99      */
100     blankText : &quot;You must select at least one item in this group&quot;,
101
102     // private
103     defaultType : 'checkboxfield',
104
105     // private
106     groupCls : Ext.baseCSSPrefix + 'form-check-group',
107
108 <span id='Ext-form.CheckboxGroup-cfg-fieldBodyCls'>    /**
109 </span>     * @cfg {String} fieldBodyCls
110      * An extra CSS class to be applied to the body content element in addition to {@link #baseBodyCls}.
111      * Defaults to 'x-form-checkboxgroup-body'.
112      */
113     fieldBodyCls: Ext.baseCSSPrefix + 'form-checkboxgroup-body',
114
115     // private
116     layout: 'checkboxgroup',
117
118     initComponent: function() {
119         var me = this;
120         me.callParent();
121         me.initField();
122     },
123
124 <span id='Ext-form.CheckboxGroup-method-initValue'>    /**
125 </span>     * @protected
126      * Initializes the field's value based on the initial config. If the {@link #value} config is specified
127      * then we use that to set the value; otherwise we initialize the originalValue by querying the values of
128      * all sub-checkboxes after they have been initialized.
129      */
130     initValue: function() {
131         var me = this,
132             valueCfg = me.value;
133         me.originalValue = me.lastValue = valueCfg || me.getValue();
134         if (valueCfg) {
135             me.setValue(valueCfg);
136         }
137     },
138
139 <span id='Ext-form.CheckboxGroup-method-onFieldAdded'>    /**
140 </span>     * @protected
141      * When a checkbox is added to the group, monitor it for changes
142      */
143     onFieldAdded: function(field) {
144         var me = this;
145         if (field.isCheckbox) {
146             me.mon(field, 'change', me.checkChange, me);
147         }
148         me.callParent(arguments);
149     },
150
151     onFieldRemoved: function(field) {
152         var me = this;
153         if (field.isCheckbox) {
154             me.mun(field, 'change', me.checkChange, me);
155         }
156         me.callParent(arguments);
157     },
158
159     // private override - the group value is a complex object, compare using object serialization
160     isEqual: function(value1, value2) {
161         var toQueryString = Ext.Object.toQueryString;
162         return toQueryString(value1) === toQueryString(value2);
163     },
164
165 <span id='Ext-form.CheckboxGroup-method-getErrors'>    /**
166 </span>     * Runs CheckboxGroup's validations and returns an array of any errors. The only error by default
167      * is if allowBlank is set to true and no items are checked.
168      * @return {Array} Array of all validation errors
169      */
170     getErrors: function() {
171         var errors = [];
172         if (!this.allowBlank &amp;&amp; Ext.isEmpty(this.getChecked())) {
173             errors.push(this.blankText);
174         }
175         return errors;
176     },
177
178 <span id='Ext-form.CheckboxGroup-method-getBoxes'>    /**
179 </span>     * @private Returns all checkbox components within the container
180      */
181     getBoxes: function() {
182         return this.query('[isCheckbox]');
183     },
184
185 <span id='Ext-form.CheckboxGroup-method-eachBox'>    /**
186 </span>     * @private Convenience function which calls the given function for every checkbox in the group
187      * @param {Function} fn The function to call
188      * @param {Object} scope Optional scope object
189      */
190     eachBox: function(fn, scope) {
191         Ext.Array.forEach(this.getBoxes(), fn, scope || this);
192     },
193
194 <span id='Ext-form.CheckboxGroup-method-getChecked'>    /**
195 </span>     * Returns an Array of all checkboxes in the container which are currently checked
196      * @return {Array} Array of Ext.form.field.Checkbox components
197      */
198     getChecked: function() {
199         return Ext.Array.filter(this.getBoxes(), function(cb) {
200             return cb.getValue();
201         });
202     },
203
204     // private override
205     isDirty: function(){
206         return Ext.Array.some(this.getBoxes(), function(cb) {
207             return cb.isDirty();
208         });
209     },
210
211     // private override
212     setReadOnly: function(readOnly) {
213         this.eachBox(function(cb) {
214             cb.setReadOnly(readOnly);
215         });
216         this.readOnly = readOnly;
217     },
218
219 <span id='Ext-form.CheckboxGroup-method-reset'>    /**
220 </span>     * Resets the checked state of all {@link Ext.form.field.Checkbox checkboxes} in the group to their
221      * originally loaded values and clears any validation messages.
222      * See {@link Ext.form.Basic}.{@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
223      */
224     reset: function() {
225         var me = this,
226             hadError = me.hasActiveError(),
227             preventMark = me.preventMark;
228         me.preventMark = true;
229         me.batchChanges(function() {
230             me.eachBox(function(cb) {
231                 cb.reset();
232             });
233         });
234         me.preventMark = preventMark;
235         me.unsetActiveError();
236         if (hadError) {
237             me.doComponentLayout();
238         }
239     },
240
241     // private override
242     resetOriginalValue: function() {
243         // Defer resetting of originalValue until after all sub-checkboxes have been reset so we get
244         // the correct data from getValue()
245         Ext.defer(function() {
246             this.callParent();
247         }, 1, this);
248     },
249
250
251 <span id='Ext-form.CheckboxGroup-method-setValue'>    /**
252 </span>     * &lt;p&gt;Sets the value(s) of all checkboxes in the group. The expected format is an Object of
253      * name-value pairs corresponding to the names of the checkboxes in the group. Each pair can
254      * have either a single or multiple values:&lt;/p&gt;
255      * &lt;ul&gt;
256      *   &lt;li&gt;A single Boolean or String value will be passed to the &lt;code&gt;setValue&lt;/code&gt; method of the
257      *   checkbox with that name. See the rules in {@link Ext.form.field.Checkbox#setValue} for accepted values.&lt;/li&gt;
258      *   &lt;li&gt;An Array of String values will be matched against the {@link Ext.form.field.Checkbox#inputValue inputValue}
259      *   of checkboxes in the group with that name; those checkboxes whose inputValue exists in the array will be
260      *   checked and others will be unchecked.&lt;/li&gt;
261      * &lt;/ul&gt;
262      * &lt;p&gt;If a checkbox's name is not in the mapping at all, it will be unchecked.&lt;/p&gt;
263      * &lt;p&gt;An example:&lt;/p&gt;
264      * &lt;pre&gt;&lt;code&gt;var myCheckboxGroup = new Ext.form.CheckboxGroup({
265     columns: 3,
266     items: [{
267         name: 'cb1',
268         boxLabel: 'Single 1'
269     }, {
270         name: 'cb2',
271         boxLabel: 'Single 2'
272     }, {
273         name: 'cb3',
274         boxLabel: 'Single 3'
275     }, {
276         name: 'cbGroup',
277         boxLabel: 'Grouped 1'
278         inputValue: 'value1'
279     }, {
280         name: 'cbGroup',
281         boxLabel: 'Grouped 2'
282         inputValue: 'value2'
283     }, {
284         name: 'cbGroup',
285         boxLabel: 'Grouped 3'
286         inputValue: 'value3'
287     }]
288 });
289
290 myCheckboxGroup.setValue({
291     cb1: true,
292     cb3: false,
293     cbGroup: ['value1', 'value3']
294 });&lt;/code&gt;&lt;/pre&gt;
295      * &lt;p&gt;The above code will cause the checkbox named 'cb1' to be checked, as well as the first and third
296      * checkboxes named 'cbGroup'. The other three checkboxes will be unchecked.&lt;/p&gt;
297      * @param {Object} value The mapping of checkbox names to values.
298      * @return {Ext.form.CheckboxGroup} this
299      */
300     setValue: function(value) {
301         var me = this;
302         me.batchChanges(function() {
303             me.eachBox(function(cb) {
304                 var name = cb.getName(),
305                     cbValue = false;
306                 if (value &amp;&amp; name in value) {
307                     if (Ext.isArray(value[name])) {
308                         cbValue = Ext.Array.contains(value[name], cb.inputValue);
309                     } else {
310                         // single value, let the checkbox's own setValue handle conversion
311                         cbValue = value[name];
312                     }
313                 }
314                 cb.setValue(cbValue);
315             });
316         });
317         return me;
318     },
319
320
321 <span id='Ext-form.CheckboxGroup-method-getValue'>    /**
322 </span>     * &lt;p&gt;Returns an object containing the values of all checked checkboxes within the group. Each key-value pair
323      * in the object corresponds to a checkbox {@link Ext.form.field.Checkbox#name name}. If there is only one checked
324      * checkbox with a particular name, the value of that pair will be the String
325      * {@link Ext.form.field.Checkbox#inputValue inputValue} of that checkbox. If there are multiple checked checkboxes
326      * with that name, the value of that pair will be an Array of the selected inputValues.&lt;/p&gt;
327      * &lt;p&gt;The object format returned from this method can also be passed directly to the {@link #setValue} method.&lt;/p&gt;
328      * &lt;p&gt;NOTE: In Ext 3, this method returned an array of Checkbox components; this was changed to make it more
329      * consistent with other field components and with the {@link #setValue} argument signature. If you need the old
330      * behavior in Ext 4+, use the {@link #getChecked} method instead.&lt;/p&gt;
331      */
332     getValue: function() {
333         var values = {};
334         this.eachBox(function(cb) {
335             var name = cb.getName(),
336                 inputValue = cb.inputValue,
337                 bucket;
338             if (cb.getValue()) {
339                 if (name in values) {
340                     bucket = values[name];
341                     if (!Ext.isArray(bucket)) {
342                         bucket = values[name] = [bucket];
343                     }
344                     bucket.push(inputValue);
345                 } else {
346                     values[name] = inputValue;
347                 }
348             }
349         });
350         return values;
351     },
352
353     /*
354      * Don't return any data for submit; the form will get the info from the individual checkboxes themselves.
355      */
356     getSubmitData: function() {
357         return null;
358     },
359
360     /*
361      * Don't return any data for the model; the form will get the info from the individual checkboxes themselves.
362      */
363     getModelData: function() {
364         return null;
365     },
366
367     validate: function() {
368         var me = this,
369             errors = me.getErrors(),
370             isValid = Ext.isEmpty(errors),
371             wasValid = !me.hasActiveError();
372
373         if (isValid) {
374             me.unsetActiveError();
375         } else {
376             me.setActiveError(errors);
377         }
378         if (isValid !== wasValid) {
379             me.fireEvent('validitychange', me, isValid);
380             me.doComponentLayout();
381         }
382
383         return isValid;
384     }
385
386 }, function() {
387
388     this.borrow(Ext.form.field.Base, ['markInvalid', 'clearInvalid']);
389
390 });
391
392 </pre></pre></body></html>