Upgrade to ExtJS 4.0.7 - Released 10/19/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  * 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.
19  *
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.
23  *
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
28  * two.)
29  *
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
33  * set up correctly.
34  *
35  * @docauthor Jason Johnston <jason@sencha.com>
36  */
37 Ext.define("Ext.form.Labelable", {
38     requires: ['Ext.XTemplate'],
39
40     /**
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.
45      */
46     labelableRenderTpl: [
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>',
51             '</label>',
52         '</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>',
56         {
57             compiled: true,
58             disableFormats: true
59         }
60     ],
61
62     /**
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.
66      */
67     activeErrorsTpl: [
68         '<tpl if="errors && errors.length">',
69             '<ul><tpl for="errors"><li<tpl if="xindex == xcount"> class="last"</tpl>>{.}</li></tpl></ul>',
70         '</tpl>'
71     ],
72
73     /**
74      * @property isFieldLabelable
75      * @type Boolean
76      * Flag denoting that this object is labelable as a field. Always true.
77      */
78     isFieldLabelable: true,
79
80     /**
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
83      * field layout.
84      */
85     formItemCls: Ext.baseCSSPrefix + 'form-item',
86
87     /**
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}.
93      */
94     labelCls: Ext.baseCSSPrefix + 'form-item-label',
95
96     /**
97      * @cfg {String} labelClsExtra
98      * An optional string of one or more additional CSS classes to add to the label element.
99      * Defaults to empty.
100      */
101
102     /**
103      * @cfg {String} [errorMsgCls='x-form-error-msg']
104      * The CSS class to be applied to the error message element.
105      */
106     errorMsgCls: Ext.baseCSSPrefix + 'form-error-msg',
107
108     /**
109      * @cfg {String} [baseBodyCls='x-form-item-body']
110      * The CSS class to be applied to the body content element.
111      */
112     baseBodyCls: Ext.baseCSSPrefix + 'form-item-body',
113
114     /**
115      * @cfg {String} fieldBodyCls
116      * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
117      */
118     fieldBodyCls: '',
119
120     /**
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.
124      */
125     clearCls: Ext.baseCSSPrefix + 'clear',
126
127     /**
128      * @cfg {String} [invalidCls='x-form-invalid']
129      * The CSS class to use when marking the component invalid.
130      */
131     invalidCls : Ext.baseCSSPrefix + 'form-invalid',
132
133     /**
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}
137      * configs.
138      */
139     fieldLabel: undefined,
140
141     /**
142      * @cfg {String} labelAlign
143      * <p>Controls the position and alignment of the {@link #fieldLabel}. Valid values are:</p>
144      * <ul>
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>
150      * </ul>
151      */
152     labelAlign : 'left',
153
154     /**
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".
158      */
159     labelWidth: 100,
160
161     /**
162      * @cfg {Number} labelPad
163      * The amount of space in pixels between the {@link #fieldLabel} and the input field.
164      */
165     labelPad : 5,
166
167     /**
168      * @cfg {String} labelSeparator
169      * Character(s) to be inserted at the end of the {@link #fieldLabel label text}.
170      */
171     labelSeparator : ':',
172
173     /**
174      * @cfg {String} labelStyle
175      * A CSS style specification string to apply directly to this field's label.
176      */
177
178     /**
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.
182      */
183     hideLabel: false,
184
185     /**
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>
193      */
194     hideEmptyLabel: true,
195
196     /**
197      * @cfg {Boolean} preventMark
198      * <tt>true</tt> to disable displaying any {@link #setActiveError error message} set on this object.
199      */
200     preventMark: false,
201
202     /**
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}.
206      */
207     autoFitErrors: true,
208
209     /**
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>
220      * </ul></div>
221      */
222     msgTarget: 'qtip',
223
224     /**
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.
229      */
230
231
232     /**
233      * Performs initialization of this mixin. Component classes using this mixin should call this method
234      * during their own initialization.
235      */
236     initLabelable: function() {
237         this.addCls(this.formItemCls);
238
239         this.addEvents(
240             /**
241              * @event errorchange
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
245              */
246             'errorchange'
247         );
248     },
249
250     /**
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
254      */
255     getFieldLabel: function() {
256         return this.fieldLabel || '';
257     },
258
259     /**
260      * @protected
261      * Generates the arguments for the field decorations {@link #labelableRenderTpl rendering template}.
262      * @return {Object} The template arguments
263      */
264     getLabelableRenderData: function() {
265         var me = this,
266             labelAlign = me.labelAlign,
267             labelCls = me.labelCls,
268             labelClsExtra = me.labelClsExtra,
269             labelPad = me.labelPad,
270             labelStyle;
271
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;';
276         } else {
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;';
281             }
282         }
283
284         return Ext.copyTo(
285             {
286                 inputId: me.getInputId(),
287                 fieldLabel: me.getFieldLabel(),
288                 labelCls: labelClsExtra ? labelCls + ' ' + labelClsExtra : labelCls,
289                 labelStyle: labelStyle + (me.labelStyle || ''),
290                 subTplMarkup: me.getSubTplMarkup()
291             },
292             me,
293             'hideLabel,hideEmptyLabel,fieldBodyCls,baseBodyCls,errorMsgCls,clearCls,labelSeparator',
294             true
295         );
296     },
297
298     onLabelableRender: function () {
299         this.addChildEls(
300             /**
301              * @property labelEl
302              * @type Ext.Element
303              * The label Element for this component. Only available after the component has been rendered.
304              */
305             'labelEl',
306
307             /**
308              * @property bodyEl
309              * @type Ext.Element
310              * The div Element wrapping the component's contents. Only available after the component has been rendered.
311              */
312             'bodyEl',
313
314             /**
315              * @property errorEl
316              * @type Ext.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'
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 {String[]} 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 {String[]} 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