Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / form / Labelable.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.form.Labelable
17
18 A mixin which allows a component to be configured and decorated with a label and/or error message as is
19 common for form fields. This is used by e.g. {@link Ext.form.field.Base} and {@link Ext.form.FieldContainer}
20 to let them be managed by the Field layout.
21
22 **NOTE**: This mixin is mainly for internal library use and most users should not need to use it directly. It
23 is more likely you will want to use one of the component classes that import this mixin, such as
24 {@link Ext.form.field.Base} or {@link Ext.form.FieldContainer}.
25
26 Use of this mixin does not make a component a field in the logical sense, meaning it does not provide any
27 logic or state related to values or validation; that is handled by the related {@link Ext.form.field.Field}
28 mixin. These two mixins may be used separately (for example {@link Ext.form.FieldContainer} is Labelable but not a
29 Field), or in combination (for example {@link Ext.form.field.Base} implements both and has logic for connecting the
30 two.)
31
32 Component classes which use this mixin should use the Field layout
33 or a derivation thereof to properly size and position the label and message according to the component config.
34 They must also call the {@link #initLabelable} method during component initialization to ensure the mixin gets
35 set up correctly.
36
37  * @markdown
38  * @docauthor Jason Johnston <jason@sencha.com>
39  */
40 Ext.define("Ext.form.Labelable", {
41     requires: ['Ext.XTemplate'],
42
43     /**
44      * @cfg {Array/String/Ext.XTemplate} labelableRenderTpl
45      * The rendering template for the field decorations. Component classes using this mixin should include
46      * logic to use this as their {@link Ext.AbstractComponent#renderTpl renderTpl}, and implement the
47      * {@link #getSubTplMarkup} method to generate the field body content.
48      */
49     labelableRenderTpl: [
50         '<tpl if="!hideLabel && !(!fieldLabel && hideEmptyLabel)">',
51             '<label<tpl if="inputId"> for="{inputId}"</tpl> class="{labelCls}"<tpl if="labelStyle"> style="{labelStyle}"</tpl>>',
52                 '<tpl if="fieldLabel">{fieldLabel}{labelSeparator}</tpl>',
53             '</label>',
54         '</tpl>',
55         '<div class="{baseBodyCls} {fieldBodyCls}"<tpl if="inputId"> id="{baseBodyCls}-{inputId}"</tpl> role="presentation">{subTplMarkup}</div>',
56         '<div class="{errorMsgCls}" style="display:none"></div>',
57         '<div class="{clearCls}" role="presentation"><!-- --></div>',
58         {
59             compiled: true,
60             disableFormats: true
61         }
62     ],
63
64     /**
65      * @cfg {Ext.XTemplate} activeErrorsTpl
66      * The template used to format the Array of error messages passed to {@link #setActiveErrors}
67      * into a single HTML string. By default this renders each message as an item in an unordered list.
68      */
69     activeErrorsTpl: [
70         '<tpl if="errors && errors.length">',
71             '<ul><tpl for="errors"><li<tpl if="xindex == xcount"> class="last"</tpl>>{.}</li></tpl></ul>',
72         '</tpl>'
73     ],
74
75     /**
76      * @property isFieldLabelable
77      * @type Boolean
78      * Flag denoting that this object is labelable as a field. Always true.
79      */
80     isFieldLabelable: true,
81
82     /**
83      * @cfg {String} formItemCls
84      * A CSS class to be applied to the outermost element to denote that it is participating in the form
85      * field layout. Defaults to 'x-form-item'.
86      */
87     formItemCls: Ext.baseCSSPrefix + 'form-item',
88
89     /**
90      * @cfg {String} labelCls
91      * The CSS class to be applied to the label element. Defaults to 'x-form-item-label'.
92      */
93     labelCls: Ext.baseCSSPrefix + 'form-item-label',
94
95     /**
96      * @cfg {String} errorMsgCls
97      * The CSS class to be applied to the error message element. Defaults to 'x-form-error-msg'.
98      */
99     errorMsgCls: Ext.baseCSSPrefix + 'form-error-msg',
100
101     /**
102      * @cfg {String} baseBodyCls
103      * The CSS class to be applied to the body content element. Defaults to 'x-form-item-body'.
104      */
105     baseBodyCls: Ext.baseCSSPrefix + 'form-item-body',
106
107     /**
108      * @cfg {String} fieldBodyCls
109      * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
110      * Defaults to empty.
111      */
112     fieldBodyCls: '',
113
114     /**
115      * @cfg {String} clearCls
116      * The CSS class to be applied to the special clearing div rendered directly after the field
117      * contents wrapper to provide field clearing (defaults to <tt>'x-clear'</tt>).
118      */
119     clearCls: Ext.baseCSSPrefix + 'clear',
120
121     /**
122      * @cfg {String} invalidCls
123      * The CSS class to use when marking the component invalid (defaults to 'x-form-invalid')
124      */
125     invalidCls : Ext.baseCSSPrefix + 'form-invalid',
126
127     /**
128      * @cfg {String} fieldLabel
129      * The label for the field. It gets appended with the {@link #labelSeparator}, and its position
130      * and sizing is determined by the {@link #labelAlign}, {@link #labelWidth}, and {@link #labelPad}
131      * configs. Defaults to undefined.
132      */
133     fieldLabel: undefined,
134
135     /**
136      * @cfg {String} labelAlign
137      * <p>Controls the position and alignment of the {@link #fieldLabel}. Valid values are:</p>
138      * <ul>
139      * <li><tt>"left"</tt> (the default) - The label is positioned to the left of the field, with its text
140      * aligned to the left. Its width is determined by the {@link #labelWidth} config.</li>
141      * <li><tt>"top"</tt> - The label is positioned above the field.</li>
142      * <li><tt>"right"</tt> - The label is positioned to the left of the field, with its text aligned
143      * to the right. Its width is determined by the {@link #labelWidth} config.</li>
144      * </ul>
145      */
146     labelAlign : 'left',
147
148     /**
149      * @cfg {Number} labelWidth
150      * The width of the {@link #fieldLabel} in pixels. Only applicable if the {@link #labelAlign} is set
151      * to "left" or "right". Defaults to <tt>100</tt>.
152      */
153     labelWidth: 100,
154
155     /**
156      * @cfg {Number} labelPad
157      * The amount of space in pixels between the {@link #fieldLabel} and the input field. Defaults to <tt>5</tt>.
158      */
159     labelPad : 5,
160
161     /**
162      * @cfg {String} labelSeparator
163      * Character(s) to be inserted at the end of the {@link #fieldLabel label text}.
164      */
165     labelSeparator : ':',
166
167     /**
168      * @cfg {String} labelStyle
169      * <p>A CSS style specification string to apply directly to this field's label. Defaults to undefined.</p>
170      */
171
172     /**
173      * @cfg {Boolean} hideLabel
174      * <p>Set to <tt>true</tt> to completely hide the label element ({@link #fieldLabel} and {@link #labelSeparator}).
175      * Defaults to <tt>false</tt>.</p>
176      * <p>Also see {@link #hideEmptyLabel}, which controls whether space will be reserved for an empty fieldLabel.</p>
177      */
178     hideLabel: false,
179
180     /**
181      * @cfg {Boolean} hideEmptyLabel
182      * <p>When set to <tt>true</tt>, the label element ({@link #fieldLabel} and {@link #labelSeparator}) will be
183      * automatically hidden if the {@link #fieldLabel} is empty. Setting this to <tt>false</tt> will cause the empty
184      * label element to be rendered and space to be reserved for it; this is useful if you want a field without a label
185      * to line up with other labeled fields in the same form. Defaults to <tt>true</tt>.</p>
186      * <p>If you wish to unconditionall hide the label even if a non-empty fieldLabel is configured, then set
187      * the {@link #hideLabel} config to <tt>true</tt>.</p>
188      */
189     hideEmptyLabel: true,
190
191     /**
192      * @cfg {Boolean} preventMark
193      * <tt>true</tt> to disable displaying any {@link #setActiveError error message} set on this object.
194      * Defaults to <tt>false</tt>.
195      */
196     preventMark: false,
197
198     /**
199      * @cfg {Boolean} autoFitErrors
200      * Whether to adjust the component's body area to make room for 'side' or 'under'
201      * {@link #msgTarget error messages}. Defaults to <tt>true</tt>.
202      */
203     autoFitErrors: true,
204
205     /**
206      * @cfg {String} msgTarget <p>The location where the error message text should display.
207      * Must be one of the following values:</p>
208      * <div class="mdetail-params"><ul>
209      * <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
210      * <div class="subdesc"><b>{@link Ext.tip.QuickTipManager#init Ext.tip.QuickTipManager.init} must have been called for this setting to work.</b></div></li>
211      * <li><code>title</code> Display the message in a default browser title attribute popup.</li>
212      * <li><code>under</code> Add a block div beneath the field containing the error message.</li>
213      * <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
214      * <li><code>none</code> Don't display any error message. This might be useful if you are implementing custom error display.</li>
215      * <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
216      * </ul></div>
217      */
218     msgTarget: 'qtip',
219
220     /**
221      * @cfg {String} activeError
222      * If specified, then the component will be displayed with this value as its active error when
223      * first rendered. Defaults to undefined. Use {@link #setActiveError} or {@link #unsetActiveError} to
224      * change it after component creation.
225      */
226
227
228     /**
229      * Performs initialization of this mixin. Component classes using this mixin should call this method
230      * during their own initialization.
231      */
232     initLabelable: function() {
233         this.addCls(this.formItemCls);
234
235         this.addEvents(
236             /**
237              * @event errorchange
238              * Fires when the active error message is changed via {@link #setActiveError}.
239              * @param {Ext.form.Labelable} this
240              * @param {String} error The active error message
241              */
242             'errorchange'
243         );
244     },
245
246     /**
247      * Returns the label for the field. Defaults to simply returning the {@link #fieldLabel} config. Can be
248      * overridden to provide
249      * @return {String} The configured field label, or empty string if not defined
250      */
251     getFieldLabel: function() {
252         return this.fieldLabel || '';
253     },
254
255     /**
256      * @protected
257      * Generates the arguments for the field decorations {@link #labelableRenderTpl rendering template}.
258      * @return {Object} The template arguments
259      */
260     getLabelableRenderData: function() {
261         var me = this,
262             labelAlign = me.labelAlign,
263             labelPad = me.labelPad,
264             labelStyle;
265
266         // Calculate label styles up front rather than in the Field layout for speed; this
267         // is safe because label alignment/width/pad are not expected to change.
268         if (labelAlign === 'top') {
269             labelStyle = 'margin-bottom:' + labelPad + 'px;';
270         } else {
271             labelStyle = 'margin-right:' + labelPad + 'px;';
272             // Add the width for border-box browsers; will be set by the Field layout for content-box
273             if (Ext.isBorderBox) {
274                 labelStyle += 'width:' + me.labelWidth + 'px;';
275             }
276         }
277
278         return Ext.copyTo(
279             {
280                 inputId: me.getInputId(),
281                 fieldLabel: me.getFieldLabel(),
282                 labelStyle: labelStyle + (me.labelStyle || ''),
283                 subTplMarkup: me.getSubTplMarkup()
284             },
285             me,
286             'hideLabel,hideEmptyLabel,labelCls,fieldBodyCls,baseBodyCls,errorMsgCls,clearCls,labelSeparator',
287             true
288         );
289     },
290
291     /**
292      * @protected
293      * Returns the additional {@link Ext.AbstractComponent#renderSelectors} for selecting the field
294      * decoration elements from the rendered {@link #labelableRenderTpl}. Component classes using this mixin should
295      * be sure and merge this method's result into the component's {@link Ext.AbstractComponent#renderSelectors}
296      * before rendering.
297      */
298     getLabelableSelectors: function() {
299         return {
300             /**
301              * @property labelEl
302              * @type Ext.core.Element
303              * The label Element for this component. Only available after the component has been rendered.
304              */
305             labelEl: 'label.' + this.labelCls,
306
307             /**
308              * @property bodyEl
309              * @type Ext.core.Element
310              * The div Element wrapping the component's contents. Only available after the component has been rendered.
311              */
312             bodyEl: '.' + this.baseBodyCls,
313
314             /**
315              * @property errorEl
316              * @type Ext.core.Element
317              * The div Element that will contain the component's error message(s). Note that depending on the
318              * configured {@link #msgTarget}, this element may be hidden in favor of some other form of
319              * presentation, but will always be present in the DOM for use by assistive technologies.
320              */
321             errorEl: '.' + this.errorMsgCls
322         };
323     },
324
325     /**
326      * @protected
327      * Gets the markup to be inserted into the outer template's bodyEl. Defaults to empty string, should
328      * be implemented by classes including this mixin as needed.
329      * @return {String} The markup to be inserted
330      */
331     getSubTplMarkup: function() {
332         return '';
333     },
334
335     /**
336      * Get the input id, if any, for this component. This is used as the "for" attribute on the label element.
337      * Implementing subclasses may also use this as e.g. the id for their own <tt>input</tt> element.
338      * @return {String} The input id
339      */
340     getInputId: function() {
341         return '';
342     },
343
344     /**
345      * Gets the active error message for this component, if any. This does not trigger
346      * validation on its own, it merely returns any message that the component may already hold.
347      * @return {String} The active error message on the component; if there is no error, an empty string is returned.
348      */
349     getActiveError : function() {
350         return this.activeError || '';
351     },
352
353     /**
354      * Tells whether the field currently has an active error message. This does not trigger
355      * validation on its own, it merely looks for any message that the component may already hold.
356      * @return {Boolean}
357      */
358     hasActiveError: function() {
359         return !!this.getActiveError();
360     },
361
362     /**
363      * Sets the active error message to the given string. This replaces the entire error message
364      * contents with the given string. Also see {@link #setActiveErrors} which accepts an Array of
365      * messages and formats them according to the {@link #activeErrorsTpl}.
366      *
367      * Note that this only updates the error message element's text and attributes, you'll have
368      * to call doComponentLayout to actually update the field's layout to match. If the field extends
369      * {@link Ext.form.field.Base} you should call {@link Ext.form.field.Base#markInvalid markInvalid} instead.
370      *
371      * @param {String} msg The error message
372      */
373     setActiveError: function(msg) {
374         this.activeError = msg;
375         this.activeErrors = [msg];
376         this.renderActiveError();
377     },
378
379     /**
380      * Gets an Array of any active error messages currently applied to the field. This does not trigger
381      * validation on its own, it merely returns any messages that the component may already hold.
382      * @return {Array} The active error messages on the component; if there are no errors, an empty Array is returned.
383      */
384     getActiveErrors: function() {
385         return this.activeErrors || [];
386     },
387
388     /**
389      * Set the active error message to an Array of error messages. The messages are formatted into
390      * a single message string using the {@link #activeErrorsTpl}. Also see {@link #setActiveError}
391      * which allows setting the entire error contents with a single string.
392      *
393      * Note that this only updates the error message element's text and attributes, you'll have
394      * to call doComponentLayout to actually update the field's layout to match. If the field extends
395      * {@link Ext.form.field.Base} you should call {@link Ext.form.field.Base#markInvalid markInvalid} instead.
396      *
397      * @param {Array} errors The error messages
398      */
399     setActiveErrors: function(errors) {
400         this.activeErrors = errors;
401         this.activeError = this.getTpl('activeErrorsTpl').apply({errors: errors});
402         this.renderActiveError();
403     },
404
405     /**
406      * Clears the active error message(s).
407      *
408      * Note that this only clears the error message element's text and attributes, you'll have
409      * to call doComponentLayout to actually update the field's layout to match. If the field extends
410      * {@link Ext.form.field.Base} you should call {@link Ext.form.field.Base#clearInvalid clearInvalid} instead.
411      */
412     unsetActiveError: function() {
413         delete this.activeError;
414         delete this.activeErrors;
415         this.renderActiveError();
416     },
417
418     /**
419      * @private
420      * Updates the rendered DOM to match the current activeError. This only updates the content and
421      * attributes, you'll have to call doComponentLayout to actually update the display.
422      */
423     renderActiveError: function() {
424         var me = this,
425             activeError = me.getActiveError(),
426             hasError = !!activeError;
427
428         if (activeError !== me.lastActiveError) {
429             me.fireEvent('errorchange', me, activeError);
430             me.lastActiveError = activeError;
431         }
432
433         if (me.rendered && !me.isDestroyed && !me.preventMark) {
434             // Add/remove invalid class
435             me.el[hasError ? 'addCls' : 'removeCls'](me.invalidCls);
436
437             // Update the aria-invalid attribute
438             me.getActionEl().dom.setAttribute('aria-invalid', hasError);
439
440             // Update the errorEl with the error message text
441             me.errorEl.dom.innerHTML = activeError;
442         }
443     },
444
445     /**
446      * Applies a set of default configuration values to this Labelable instance. For each of the
447      * properties in the given object, check if this component hasOwnProperty that config; if not
448      * then it's inheriting a default value from its prototype and we should apply the default value.
449      * @param {Object} defaults The defaults to apply to the object.
450      */
451     setFieldDefaults: function(defaults) {
452         var me = this;
453         Ext.iterate(defaults, function(key, val) {
454             if (!me.hasOwnProperty(key)) {
455                 me[key] = val;
456             }
457         });
458     },
459
460     /**
461      * @protected Calculate and return the natural width of the bodyEl. Override to provide custom logic.
462      * Note for implementors: if at all possible this method should be overridden with a custom implementation
463      * that can avoid anything that would cause the browser to reflow, e.g. querying offsetWidth.
464      */
465     getBodyNaturalWidth: function() {
466         return this.bodyEl.getWidth();
467     }
468
469 });
470