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