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 * A mixin which allows a component to be configured and decorated with a label and/or error message as is
17 * common for form fields. This is used by e.g. Ext.form.field.Base and Ext.form.FieldContainer
18 * to let them be managed by the Field layout.
20 * NOTE: This mixin is mainly for internal library use and most users should not need to use it directly. It
21 * is more likely you will want to use one of the component classes that import this mixin, such as
22 * Ext.form.field.Base or Ext.form.FieldContainer.
24 * Use of this mixin does not make a component a field in the logical sense, meaning it does not provide any
25 * logic or state related to values or validation; that is handled by the related Ext.form.field.Field
26 * mixin. These two mixins may be used separately (for example Ext.form.FieldContainer is Labelable but not a
27 * Field), or in combination (for example Ext.form.field.Base implements both and has logic for connecting the
30 * Component classes which use this mixin should use the Field layout
31 * or a derivation thereof to properly size and position the label and message according to the component config.
32 * They must also call the {@link #initLabelable} method during component initialization to ensure the mixin gets
35 * @docauthor Jason Johnston <jason@sencha.com>
37 Ext.define("Ext.form.Labelable", {
38 requires: ['Ext.XTemplate'],
41 * @cfg {String/String[]/Ext.XTemplate} labelableRenderTpl
42 * The rendering template for the field decorations. Component classes using this mixin should include
43 * logic to use this as their {@link Ext.AbstractComponent#renderTpl renderTpl}, and implement the
44 * {@link #getSubTplMarkup} method to generate the field body content.
47 '<tpl if="!hideLabel && !(!fieldLabel && hideEmptyLabel)">',
48 '<label id="{id}-labelEl"<tpl if="inputId"> for="{inputId}"</tpl> class="{labelCls}"',
49 '<tpl if="labelStyle"> style="{labelStyle}"</tpl>>',
50 '<tpl if="fieldLabel">{fieldLabel}{labelSeparator}</tpl>',
53 '<div class="{baseBodyCls} {fieldBodyCls}" id="{id}-bodyEl" role="presentation">{subTplMarkup}</div>',
54 '<div id="{id}-errorEl" class="{errorMsgCls}" style="display:none"></div>',
55 '<div class="{clearCls}" role="presentation"><!-- --></div>',
63 * @cfg {Ext.XTemplate} activeErrorsTpl
64 * The template used to format the Array of error messages passed to {@link #setActiveErrors}
65 * into a single HTML string. By default this renders each message as an item in an unordered list.
68 '<tpl if="errors && errors.length">',
69 '<ul><tpl for="errors"><li<tpl if="xindex == xcount"> class="last"</tpl>>{.}</li></tpl></ul>',
74 * @property isFieldLabelable
76 * Flag denoting that this object is labelable as a field. Always true.
78 isFieldLabelable: true,
81 * @cfg {String} [formItemCls='x-form-item']
82 * A CSS class to be applied to the outermost element to denote that it is participating in the form
85 formItemCls: Ext.baseCSSPrefix + 'form-item',
88 * @cfg {String} [labelCls='x-form-item-label']
89 * The CSS class to be applied to the label element.
90 * This (single) CSS class is used to formulate the renderSelector and drives the field
91 * layout where it is concatenated with a hyphen ('-') and {@link #labelAlign}. To add
92 * additional classes, use {@link #labelClsExtra}.
94 labelCls: Ext.baseCSSPrefix + 'form-item-label',
97 * @cfg {String} labelClsExtra
98 * An optional string of one or more additional CSS classes to add to the label element.
103 * @cfg {String} [errorMsgCls='x-form-error-msg']
104 * The CSS class to be applied to the error message element.
106 errorMsgCls: Ext.baseCSSPrefix + 'form-error-msg',
109 * @cfg {String} [baseBodyCls='x-form-item-body']
110 * The CSS class to be applied to the body content element.
112 baseBodyCls: Ext.baseCSSPrefix + 'form-item-body',
115 * @cfg {String} fieldBodyCls
116 * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
121 * @cfg {String} [clearCls='x-clear']
122 * The CSS class to be applied to the special clearing div rendered directly after the field
123 * contents wrapper to provide field clearing.
125 clearCls: Ext.baseCSSPrefix + 'clear',
128 * @cfg {String} [invalidCls='x-form-invalid']
129 * The CSS class to use when marking the component invalid.
131 invalidCls : Ext.baseCSSPrefix + 'form-invalid',
134 * @cfg {String} fieldLabel
135 * The label for the field. It gets appended with the {@link #labelSeparator}, and its position
136 * and sizing is determined by the {@link #labelAlign}, {@link #labelWidth}, and {@link #labelPad}
139 fieldLabel: undefined,
142 * @cfg {String} labelAlign
143 * <p>Controls the position and alignment of the {@link #fieldLabel}. Valid values are:</p>
145 * <li><tt>"left"</tt> (the default) - The label is positioned to the left of the field, with its text
146 * aligned to the left. Its width is determined by the {@link #labelWidth} config.</li>
147 * <li><tt>"top"</tt> - The label is positioned above the field.</li>
148 * <li><tt>"right"</tt> - The label is positioned to the left of the field, with its text aligned
149 * to the right. Its width is determined by the {@link #labelWidth} config.</li>
155 * @cfg {Number} labelWidth
156 * The width of the {@link #fieldLabel} in pixels. Only applicable if the {@link #labelAlign} is set
157 * to "left" or "right".
162 * @cfg {Number} labelPad
163 * The amount of space in pixels between the {@link #fieldLabel} and the input field.
168 * @cfg {String} labelSeparator
169 * Character(s) to be inserted at the end of the {@link #fieldLabel label text}.
171 labelSeparator : ':',
174 * @cfg {String} labelStyle
175 * A CSS style specification string to apply directly to this field's label.
179 * @cfg {Boolean} hideLabel
180 * Set to true to completely hide the label element ({@link #fieldLabel} and {@link #labelSeparator}).
181 * Also see {@link #hideEmptyLabel}, which controls whether space will be reserved for an empty fieldLabel.
186 * @cfg {Boolean} hideEmptyLabel
187 * <p>When set to <tt>true</tt>, the label element ({@link #fieldLabel} and {@link #labelSeparator}) will be
188 * automatically hidden if the {@link #fieldLabel} is empty. Setting this to <tt>false</tt> will cause the empty
189 * label element to be rendered and space to be reserved for it; this is useful if you want a field without a label
190 * to line up with other labeled fields in the same form.</p>
191 * <p>If you wish to unconditionall hide the label even if a non-empty fieldLabel is configured, then set
192 * the {@link #hideLabel} config to <tt>true</tt>.</p>
194 hideEmptyLabel: true,
197 * @cfg {Boolean} preventMark
198 * <tt>true</tt> to disable displaying any {@link #setActiveError error message} set on this object.
203 * @cfg {Boolean} autoFitErrors
204 * Whether to adjust the component's body area to make room for 'side' or 'under'
205 * {@link #msgTarget error messages}.
210 * @cfg {String} msgTarget <p>The location where the error message text should display.
211 * Must be one of the following values:</p>
212 * <div class="mdetail-params"><ul>
213 * <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
214 * <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>
215 * <li><code>title</code> Display the message in a default browser title attribute popup.</li>
216 * <li><code>under</code> Add a block div beneath the field containing the error message.</li>
217 * <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
218 * <li><code>none</code> Don't display any error message. This might be useful if you are implementing custom error display.</li>
219 * <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
225 * @cfg {String} activeError
226 * If specified, then the component will be displayed with this value as its active error when
227 * first rendered. Use {@link #setActiveError} or {@link #unsetActiveError} to
228 * change it after component creation.
233 * Performs initialization of this mixin. Component classes using this mixin should call this method
234 * during their own initialization.
236 initLabelable: function() {
237 this.addCls(this.formItemCls);
242 * Fires when the active error message is changed via {@link #setActiveError}.
243 * @param {Ext.form.Labelable} this
244 * @param {String} error The active error message
251 * Returns the label for the field. Defaults to simply returning the {@link #fieldLabel} config. Can be
252 * overridden to provide
253 * @return {String} The configured field label, or empty string if not defined
255 getFieldLabel: function() {
256 return this.fieldLabel || '';
261 * Generates the arguments for the field decorations {@link #labelableRenderTpl rendering template}.
262 * @return {Object} The template arguments
264 getLabelableRenderData: function() {
266 labelAlign = me.labelAlign,
267 labelCls = me.labelCls,
268 labelClsExtra = me.labelClsExtra,
269 labelPad = me.labelPad,
272 // Calculate label styles up front rather than in the Field layout for speed; this
273 // is safe because label alignment/width/pad are not expected to change.
274 if (labelAlign === 'top') {
275 labelStyle = 'margin-bottom:' + labelPad + 'px;';
277 labelStyle = 'margin-right:' + labelPad + 'px;';
278 // Add the width for border-box browsers; will be set by the Field layout for content-box
279 if (Ext.isBorderBox) {
280 labelStyle += 'width:' + me.labelWidth + 'px;';
286 inputId: me.getInputId(),
287 fieldLabel: me.getFieldLabel(),
288 labelCls: labelClsExtra ? labelCls + ' ' + labelClsExtra : labelCls,
289 labelStyle: labelStyle + (me.labelStyle || ''),
290 subTplMarkup: me.getSubTplMarkup()
293 'hideLabel,hideEmptyLabel,fieldBodyCls,baseBodyCls,errorMsgCls,clearCls,labelSeparator',
298 onLabelableRender: function () {
303 * The label Element for this component. Only available after the component has been rendered.
310 * The div Element wrapping the component's contents. Only available after the component has been rendered.
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.
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 {String[]} 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 {String[]} 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();