Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / form / field / Checkbox.js
1 /**
2  * @class Ext.form.field.Checkbox
3  * @extends Ext.form.field.Base
4
5 Single checkbox field. Can be used as a direct replacement for traditional checkbox fields. Also serves as a
6 parent class for {@link Ext.form.field.Radio radio buttons}.
7
8 __Labeling:__ In addition to the {@link Ext.form.Labelable standard field labeling options}, checkboxes
9 may be given an optional {@link #boxLabel} which will be displayed immediately after checkbox. Also see
10 {@link Ext.form.CheckboxGroup} for a convenient method of grouping related checkboxes.
11
12 __Values:__
13 The main value of a checkbox is a boolean, indicating whether or not the checkbox is checked.
14 The following values will check the checkbox:
15 * `true`
16 * `'true'`
17 * `'1'`
18 * `'on'`
19
20 Any other value will uncheck the checkbox.
21
22 In addition to the main boolean value, you may also specify a separate {@link #inputValue}. This will be
23 sent as the parameter value when the form is {@link Ext.form.Basic#submit submitted}. You will want to set
24 this value if you have multiple checkboxes with the same {@link #name}. If not specified, the value `on`
25 will be used.
26 {@img Ext.form.Checkbox/Ext.form.Checkbox.png Ext.form.Checkbox Checkbox component}
27 __Example usage:__
28
29     Ext.create('Ext.form.Panel', {
30         bodyPadding: 10,
31         width      : 300,
32         title      : 'Pizza Order',
33         items: [
34             {
35                 xtype      : 'fieldcontainer',
36                 fieldLabel : 'Toppings',
37                 defaultType: 'checkboxfield',
38                 items: [
39                     {
40                         boxLabel  : 'Anchovies',
41                         name      : 'topping',
42                         inputValue: '1',
43                         id        : 'checkbox1'
44                     }, {
45                         boxLabel  : 'Artichoke Hearts',
46                         name      : 'topping',
47                         inputValue: '2',
48                         checked   : true,
49                         id        : 'checkbox2'
50                     }, {
51                         boxLabel  : 'Bacon',
52                         name      : 'topping',
53                         inputValue: '3',
54                         id        : 'checkbox3'
55                     }
56                 ]
57             }
58         ],
59         bbar: [
60             {
61                 text: 'Select Bacon',
62                 handler: function() {
63                     var checkbox = Ext.getCmp('checkbox3');
64                     checkbox.setValue(true);
65                 }
66             },
67             '-',
68             {
69                 text: 'Select All',
70                 handler: function() {
71                     var checkbox1 = Ext.getCmp('checkbox1'),
72                         checkbox2 = Ext.getCmp('checkbox2'),
73                         checkbox3 = Ext.getCmp('checkbox3');
74     
75                     checkbox1.setValue(true);
76                     checkbox2.setValue(true);
77                     checkbox3.setValue(true);
78                 }
79             },
80             {
81                 text: 'Deselect All',
82                 handler: function() {
83                     var checkbox1 = Ext.getCmp('checkbox1'),
84                         checkbox2 = Ext.getCmp('checkbox2'),
85                         checkbox3 = Ext.getCmp('checkbox3');
86     
87                     checkbox1.setValue(false);
88                     checkbox2.setValue(false);
89                     checkbox3.setValue(false);
90                 }
91             }
92         ],
93         renderTo: Ext.getBody()
94     });
95
96  * @constructor
97  * Creates a new Checkbox
98  * @param {Object} config Configuration options
99  * @xtype checkboxfield
100  * @docauthor Robert Dougan <rob@sencha.com>
101  * @markdown
102  */
103 Ext.define('Ext.form.field.Checkbox', {
104     extend: 'Ext.form.field.Base',
105     alias: ['widget.checkboxfield', 'widget.checkbox'],
106     alternateClassName: 'Ext.form.Checkbox',
107     requires: ['Ext.XTemplate', 'Ext.form.CheckboxManager'],
108
109     fieldSubTpl: [
110         '<tpl if="boxLabel && boxLabelAlign == \'before\'">',
111             '<label class="{boxLabelCls} {boxLabelCls}-{boxLabelAlign}" for="{id}">{boxLabel}</label>',
112         '</tpl>',
113         // Creates not an actual checkbox, but a button which is given aria role="checkbox" and
114         // styled with a custom checkbox image. This allows greater control and consistency in
115         // styling, and using a button allows it to gain focus and handle keyboard nav properly.
116         '<input type="button" id="{id}" ',
117             '<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
118             'class="{fieldCls} {typeCls}" autocomplete="off" hidefocus="true" />',
119         '<tpl if="boxLabel && boxLabelAlign == \'after\'">',
120             '<label class="{boxLabelCls} {boxLabelCls}-{boxLabelAlign}" for="{id}">{boxLabel}</label>',
121         '</tpl>',
122         {
123             disableFormats: true,
124             compiled: true
125         }
126     ],
127
128     isCheckbox: true,
129
130     /**
131      * @cfg {String} focusCls The CSS class to use when the checkbox receives focus
132      * (defaults to <tt>'x-form-cb-focus'</tt>)
133      */
134     focusCls: Ext.baseCSSPrefix + 'form-cb-focus',
135
136     /**
137      * @cfg {String} fieldCls The default CSS class for the checkbox (defaults to <tt>'x-form-field'</tt>)
138      */
139
140     /**
141      * @cfg {String} fieldBodyCls
142      * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
143      * Defaults to 'x-form-cb-wrap.
144      */
145     fieldBodyCls: Ext.baseCSSPrefix + 'form-cb-wrap',
146
147     /**
148      * @cfg {Boolean} checked <tt>true</tt> if the checkbox should render initially checked (defaults to <tt>false</tt>)
149      */
150     checked: false,
151
152     /**
153      * @cfg {String} checkedCls The CSS class added to the component's main element when it is in the checked state.
154      */
155     checkedCls: Ext.baseCSSPrefix + 'form-cb-checked',
156
157     /**
158      * @cfg {String} boxLabel An optional text label that will appear next to the checkbox. Whether it appears before
159      * or after the checkbox is determined by the {@link #boxLabelAlign} config (defaults to after).
160      */
161
162     /**
163      * @cfg {String} boxLabelCls The CSS class to be applied to the {@link #boxLabel} element
164      */
165     boxLabelCls: Ext.baseCSSPrefix + 'form-cb-label',
166
167     /**
168      * @cfg {String} boxLabelAlign The position relative to the checkbox where the {@link #boxLabel} should
169      * appear. Recognized values are <tt>'before'</tt> and <tt>'after'</tt>. Defaults to <tt>'after'</tt>.
170      */
171     boxLabelAlign: 'after',
172
173     /**
174      * @cfg {String} inputValue The value that should go into the generated input element's value attribute and
175      * should be used as the parameter value when submitting as part of a form. Defaults to <tt>"on"</tt>.
176      */
177     inputValue: 'on',
178
179     /**
180      * @cfg {String} uncheckedValue If configured, this will be submitted as the checkbox's value during form
181      * submit if the checkbox is unchecked. By default this is undefined, which results in nothing being
182      * submitted for the checkbox field when the form is submitted (the default behavior of HTML checkboxes).
183      */
184
185     /**
186      * @cfg {Function} handler A function called when the {@link #checked} value changes (can be used instead of
187      * handling the {@link #change change event}). The handler is passed the following parameters:
188      * <div class="mdetail-params"><ul>
189      * <li><b>checkbox</b> : Ext.form.field.Checkbox<div class="sub-desc">The Checkbox being toggled.</div></li>
190      * <li><b>checked</b> : Boolean<div class="sub-desc">The new checked state of the checkbox.</div></li>
191      * </ul></div>
192      */
193
194     /**
195      * @cfg {Object} scope An object to use as the scope ('this' reference) of the {@link #handler} function
196      * (defaults to this Checkbox).
197      */
198
199     // private overrides
200     checkChangeEvents: [],
201     inputType: 'checkbox',
202     ariaRole: 'checkbox',
203
204     // private
205     onRe: /^on$/i,
206
207     initComponent: function(){
208         this.callParent(arguments);
209         this.getManager().add(this);
210     },
211
212     initValue: function() {
213         var me = this,
214             checked = !!me.checked;
215
216         /**
217          * The original value of the field as configured in the {@link #checked} configuration, or
218          * as loaded by the last form load operation if the form's {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
219          * setting is <code>true</code>.
220          * @type Mixed
221          * @property originalValue
222          */
223         me.originalValue = me.lastValue = checked;
224
225         // Set the initial checked state
226         me.setValue(checked);
227     },
228
229     // private
230     onRender : function(ct, position) {
231         var me = this;
232         Ext.applyIf(me.renderSelectors, {
233             /**
234              * @property boxLabelEl
235              * @type Ext.core.Element
236              * A reference to the label element created for the {@link #boxLabel}. Only present if the
237              * component has been rendered and has a boxLabel configured.
238              */
239             boxLabelEl: 'label.' + me.boxLabelCls
240         });
241         Ext.applyIf(me.subTplData, {
242             boxLabel: me.boxLabel,
243             boxLabelCls: me.boxLabelCls,
244             boxLabelAlign: me.boxLabelAlign
245         });
246
247         me.callParent(arguments);
248     },
249
250     initEvents: function() {
251         var me = this;
252         me.callParent();
253         me.mon(me.inputEl, 'click', me.onBoxClick, me);
254     },
255
256     /**
257      * @private Handle click on the checkbox button
258      */
259     onBoxClick: function(e) {
260         var me = this;
261         if (!me.disabled && !me.readOnly) {
262             this.setValue(!this.checked);
263         }
264     },
265
266     /**
267      * Returns the checked state of the checkbox.
268      * @return {Boolean} True if checked, else false
269      */
270     getRawValue: function() {
271         return this.checked;
272     },
273
274     /**
275      * Returns the checked state of the checkbox.
276      * @return {Boolean} True if checked, else false
277      */
278     getValue: function() {
279         return this.checked;
280     },
281
282     /**
283      * Returns the submit value for the checkbox which can be used when submitting forms.
284      * @return {Boolean/null} True if checked; otherwise either the {@link #uncheckedValue} or null.
285      */
286     getSubmitValue: function() {
287         return this.checked ? this.inputValue : (this.uncheckedValue || null);
288     },
289
290     getModelData: function() {
291         return this.getSubmitData();
292     },
293
294     /**
295      * Sets the checked state of the checkbox.
296      * @param {Boolean/String} value The following values will check the checkbox:
297      * <code>true, 'true', '1', or 'on'</code>, as well as a String that matches the {@link #inputValue}.
298      * Any other value will uncheck the checkbox.
299      * @return {Boolean} the new checked state of the checkbox
300      */
301     setRawValue: function(value) {
302         var me = this,
303             inputEl = me.inputEl,
304             inputValue = me.inputValue,
305             checked = (value === true || value === 'true' || value === '1' ||
306                       ((Ext.isString(value) && inputValue) ? value == inputValue : me.onRe.test(value)));
307
308         if (inputEl) {
309             inputEl.dom.setAttribute('aria-checked', checked);
310             me[checked ? 'addCls' : 'removeCls'](me.checkedCls);
311         }
312
313         me.checked = me.rawValue = checked;
314         return checked;
315     },
316
317     /**
318      * Sets the checked state of the checkbox, and invokes change detection.
319      * @param {Boolean/String} checked The following values will check the checkbox:
320      * <code>true, 'true', '1', or 'on'</code>, as well as a String that matches the {@link #inputValue}.
321      * Any other value will uncheck the checkbox.
322      * @return {Ext.form.field.Checkbox} this
323      */
324     setValue: function(checked) {
325         var me = this;
326
327         // If an array of strings is passed, find all checkboxes in the group with the same name as this
328         // one and check all those whose inputValue is in the array, unchecking all the others. This is to
329         // facilitate setting values from Ext.form.Basic#setValues, but is not publicly documented as we
330         // don't want users depending on this behavior.
331         if (Ext.isArray(checked)) {
332             me.getManager().getByName(me.name).each(function(cb) {
333                 cb.setValue(Ext.Array.contains(checked, cb.inputValue));
334             });
335         } else {
336             me.callParent(arguments);
337         }
338
339         return me;
340     },
341
342     // private
343     valueToRaw: function(value) {
344         // No extra conversion for checkboxes
345         return value;
346     },
347
348     /**
349      * @private
350      * Called when the checkbox's checked state changes. Invokes the {@link #handler} callback
351      * function if specified.
352      */
353     onChange: function(newVal, oldVal) {
354         var me = this,
355             handler = me.handler;
356         if (handler) {
357             handler.call(me.scope || me, me, newVal);
358         }
359         me.callParent(arguments);
360     },
361
362     // inherit docs
363     getManager: function() {
364         return Ext.form.CheckboxManager;
365     },
366
367     onEnable: function() {
368         var me = this,
369             inputEl = me.inputEl;
370         me.callParent();
371         if (inputEl) {
372             // Can still be disabled if the field is readOnly
373             inputEl.dom.disabled = me.readOnly;
374         }
375     },
376
377     setReadOnly: function(readOnly) {
378         var me = this,
379             inputEl = me.inputEl;
380         if (inputEl) {
381             // Set the button to disabled when readonly
382             inputEl.dom.disabled = readOnly || me.disabled;
383         }
384         me.readOnly = readOnly;
385     },
386
387     /**
388      * @protected Calculate and return the natural width of the bodyEl. It's possible that the initial
389      * rendering will cause the boxLabel to wrap and give us a bad width, so we must prevent wrapping
390      * while measuring.
391      */
392     getBodyNaturalWidth: function() {
393         var me = this,
394             bodyEl = me.bodyEl,
395             ws = 'white-space',
396             width;
397         bodyEl.setStyle(ws, 'nowrap');
398         width = bodyEl.getWidth();
399         bodyEl.setStyle(ws, '');
400         return width;
401     }
402
403 });