3 This file is part of Ext JS 4
5 Copyright (c) 2011 Sencha Inc
7 Contact: http://www.sencha.com/contact
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.
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
16 * @class Ext.form.Labelable
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.
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}.
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
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
38 * @docauthor Jason Johnston <jason@sencha.com>
40 Ext.define("Ext.form.Labelable", {
41 requires: ['Ext.XTemplate'],
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.
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>',
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>',
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.
70 '<tpl if="errors && errors.length">',
71 '<ul><tpl for="errors"><li<tpl if="xindex == xcount"> class="last"</tpl>>{.}</li></tpl></ul>',
76 * @property isFieldLabelable
78 * Flag denoting that this object is labelable as a field. Always true.
80 isFieldLabelable: true,
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'.
87 formItemCls: Ext.baseCSSPrefix + 'form-item',
90 * @cfg {String} labelCls
91 * The CSS class to be applied to the label element. Defaults to 'x-form-item-label'.
93 labelCls: Ext.baseCSSPrefix + 'form-item-label',
96 * @cfg {String} errorMsgCls
97 * The CSS class to be applied to the error message element. Defaults to 'x-form-error-msg'.
99 errorMsgCls: Ext.baseCSSPrefix + 'form-error-msg',
102 * @cfg {String} baseBodyCls
103 * The CSS class to be applied to the body content element. Defaults to 'x-form-item-body'.
105 baseBodyCls: Ext.baseCSSPrefix + 'form-item-body',
108 * @cfg {String} fieldBodyCls
109 * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
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>).
119 clearCls: Ext.baseCSSPrefix + 'clear',
122 * @cfg {String} invalidCls
123 * The CSS class to use when marking the component invalid (defaults to 'x-form-invalid')
125 invalidCls : Ext.baseCSSPrefix + 'form-invalid',
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.
133 fieldLabel: undefined,
136 * @cfg {String} labelAlign
137 * <p>Controls the position and alignment of the {@link #fieldLabel}. Valid values are:</p>
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>
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>.
156 * @cfg {Number} labelPad
157 * The amount of space in pixels between the {@link #fieldLabel} and the input field. Defaults to <tt>5</tt>.
162 * @cfg {String} labelSeparator
163 * Character(s) to be inserted at the end of the {@link #fieldLabel label text}.
165 labelSeparator : ':',
168 * @cfg {String} labelStyle
169 * <p>A CSS style specification string to apply directly to this field's label. Defaults to undefined.</p>
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>
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>
189 hideEmptyLabel: true,
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>.
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>.
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>
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.
229 * Performs initialization of this mixin. Component classes using this mixin should call this method
230 * during their own initialization.
232 initLabelable: function() {
233 this.addCls(this.formItemCls);
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
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
251 getFieldLabel: function() {
252 return this.fieldLabel || '';
257 * Generates the arguments for the field decorations {@link #labelableRenderTpl rendering template}.
258 * @return {Object} The template arguments
260 getLabelableRenderData: function() {
262 labelAlign = me.labelAlign,
263 labelPad = me.labelPad,
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;';
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;';
280 inputId: me.getInputId(),
281 fieldLabel: me.getFieldLabel(),
282 labelStyle: labelStyle + (me.labelStyle || ''),
283 subTplMarkup: me.getSubTplMarkup()
286 'hideLabel,hideEmptyLabel,labelCls,fieldBodyCls,baseBodyCls,errorMsgCls,clearCls,labelSeparator',
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}
298 getLabelableSelectors: function() {
302 * @type Ext.core.Element
303 * The label Element for this component. Only available after the component has been rendered.
305 labelEl: 'label.' + this.labelCls,
309 * @type Ext.core.Element
310 * The div Element wrapping the component's contents. Only available after the component has been rendered.
312 bodyEl: '.' + this.baseBodyCls,
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.
321 errorEl: '.' + this.errorMsgCls
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
331 getSubTplMarkup: function() {
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
340 getInputId: function() {
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.
349 getActiveError : function() {
350 return this.activeError || '';
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.
358 hasActiveError: function() {
359 return !!this.getActiveError();
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}.
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.
371 * @param {String} msg The error message
373 setActiveError: function(msg) {
374 this.activeError = msg;
375 this.activeErrors = [msg];
376 this.renderActiveError();
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.
384 getActiveErrors: function() {
385 return this.activeErrors || [];
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.
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.
397 * @param {Array} errors The error messages
399 setActiveErrors: function(errors) {
400 this.activeErrors = errors;
401 this.activeError = this.getTpl('activeErrorsTpl').apply({errors: errors});
402 this.renderActiveError();
406 * Clears the active error message(s).
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.
412 unsetActiveError: function() {
413 delete this.activeError;
414 delete this.activeErrors;
415 this.renderActiveError();
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.
423 renderActiveError: function() {
425 activeError = me.getActiveError(),
426 hasError = !!activeError;
428 if (activeError !== me.lastActiveError) {
429 me.fireEvent('errorchange', me, activeError);
430 me.lastActiveError = activeError;
433 if (me.rendered && !me.isDestroyed && !me.preventMark) {
434 // Add/remove invalid class
435 me.el[hasError ? 'addCls' : 'removeCls'](me.invalidCls);
437 // Update the aria-invalid attribute
438 me.getActionEl().dom.setAttribute('aria-invalid', hasError);
440 // Update the errorEl with the error message text
441 me.errorEl.dom.innerHTML = activeError;
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.
451 setFieldDefaults: function(defaults) {
453 Ext.iterate(defaults, function(key, val) {
454 if (!me.hasOwnProperty(key)) {
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.
465 getBodyNaturalWidth: function() {
466 return this.bodyEl.getWidth();