Upgrade to ExtJS 4.0.1 - Released 05/18/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         var unchecked = this.uncheckedValue,
288             uncheckedVal = Ext.isDefined(unchecked) ? unchecked : null;
289         return this.checked ? this.inputValue : uncheckedVal;
290     },
291
292     /**
293      * Sets the checked state of the checkbox.
294      * @param {Boolean/String} value The following values will check the checkbox:
295      * <code>true, 'true', '1', or 'on'</code>, as well as a String that matches the {@link #inputValue}.
296      * Any other value will uncheck the checkbox.
297      * @return {Boolean} the new checked state of the checkbox
298      */
299     setRawValue: function(value) {
300         var me = this,
301             inputEl = me.inputEl,
302             inputValue = me.inputValue,
303             checked = (value === true || value === 'true' || value === '1' ||
304                       ((Ext.isString(value) && inputValue) ? value == inputValue : me.onRe.test(value)));
305
306         if (inputEl) {
307             inputEl.dom.setAttribute('aria-checked', checked);
308             me[checked ? 'addCls' : 'removeCls'](me.checkedCls);
309         }
310
311         me.checked = me.rawValue = checked;
312         return checked;
313     },
314
315     /**
316      * Sets the checked state of the checkbox, and invokes change detection.
317      * @param {Boolean/String} checked The following values will check the checkbox:
318      * <code>true, 'true', '1', or 'on'</code>, as well as a String that matches the {@link #inputValue}.
319      * Any other value will uncheck the checkbox.
320      * @return {Ext.form.field.Checkbox} this
321      */
322     setValue: function(checked) {
323         var me = this;
324
325         // If an array of strings is passed, find all checkboxes in the group with the same name as this
326         // one and check all those whose inputValue is in the array, unchecking all the others. This is to
327         // facilitate setting values from Ext.form.Basic#setValues, but is not publicly documented as we
328         // don't want users depending on this behavior.
329         if (Ext.isArray(checked)) {
330             me.getManager().getByName(me.name).each(function(cb) {
331                 cb.setValue(Ext.Array.contains(checked, cb.inputValue));
332             });
333         } else {
334             me.callParent(arguments);
335         }
336
337         return me;
338     },
339
340     // private
341     valueToRaw: function(value) {
342         // No extra conversion for checkboxes
343         return value;
344     },
345
346     /**
347      * @private
348      * Called when the checkbox's checked state changes. Invokes the {@link #handler} callback
349      * function if specified.
350      */
351     onChange: function(newVal, oldVal) {
352         var me = this,
353             handler = me.handler;
354         if (handler) {
355             handler.call(me.scope || me, me, newVal);
356         }
357         me.callParent(arguments);
358     },
359
360     // inherit docs
361     getManager: function() {
362         return Ext.form.CheckboxManager;
363     },
364
365     onEnable: function() {
366         var me = this,
367             inputEl = me.inputEl;
368         me.callParent();
369         if (inputEl) {
370             // Can still be disabled if the field is readOnly
371             inputEl.dom.disabled = me.readOnly;
372         }
373     },
374
375     setReadOnly: function(readOnly) {
376         var me = this,
377             inputEl = me.inputEl;
378         if (inputEl) {
379             // Set the button to disabled when readonly
380             inputEl.dom.disabled = readOnly || me.disabled;
381         }
382         me.readOnly = readOnly;
383     },
384
385     /**
386      * @protected Calculate and return the natural width of the bodyEl. It's possible that the initial
387      * rendering will cause the boxLabel to wrap and give us a bad width, so we must prevent wrapping
388      * while measuring.
389      */
390     getBodyNaturalWidth: function() {
391         var me = this,
392             bodyEl = me.bodyEl,
393             ws = 'white-space',
394             width;
395         bodyEl.setStyle(ws, 'nowrap');
396         width = bodyEl.getWidth();
397         bodyEl.setStyle(ws, '');
398         return width;
399     }
400
401 });