Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / form / field / Field.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.field.Field
17
18 This mixin provides a common interface for the logical behavior and state of form fields, including:
19
20 - Getter and setter methods for field values
21 - Events and methods for tracking value and validity changes
22 - Methods for triggering validation
23
24 **NOTE**: When implementing custom fields, it is most likely that you will want to extend the {@link Ext.form.field.Base}
25 component class rather than using this mixin directly, as BaseField contains additional logic for generating an
26 actual DOM complete with {@link Ext.form.Labelable label and error message} display and a form input field,
27 plus methods that bind the Field value getters and setters to the input field's value.
28
29 If you do want to implement this mixin directly and don't want to extend {@link Ext.form.field.Base}, then
30 you will most likely want to override the following methods with custom implementations: {@link #getValue},
31 {@link #setValue}, and {@link #getErrors}. Other methods may be overridden as needed but their base
32 implementations should be sufficient for common cases. You will also need to make sure that {@link #initField}
33 is called during the component's initialization.
34
35  * @markdown
36  * @docauthor Jason Johnston <jason@sencha.com>
37  */
38 Ext.define('Ext.form.field.Field', {
39
40     /**
41      * @property isFormField
42      * @type {Boolean}
43      * Flag denoting that this component is a Field. Always true.
44      */
45     isFormField : true,
46
47     /**
48      * @cfg {Mixed} value A value to initialize this field with (defaults to undefined).
49      */
50     
51     /**
52      * @cfg {String} name The name of the field (defaults to undefined). By default this is used as the parameter
53      * name when including the {@link #getSubmitData field value} in a {@link Ext.form.Basic#submit form submit()}.
54      * To prevent the field from being included in the form submit, set {@link #submitValue} to <tt>false</tt>.
55      */
56
57     /**
58      * @cfg {Boolean} disabled True to disable the field (defaults to false). Disabled Fields will not be
59      * {@link Ext.form.Basic#submit submitted}.</p>
60      */
61     disabled : false,
62
63     /**
64      * @cfg {Boolean} submitValue Setting this to <tt>false</tt> will prevent the field from being
65      * {@link Ext.form.Basic#submit submitted} even when it is not disabled. Defaults to <tt>true</tt>.
66      */
67     submitValue: true,
68
69     /**
70      * @cfg {Boolean} validateOnChange
71      * <p>Specifies whether this field should be validated immediately whenever a change in its value is detected.
72      * Defaults to <tt>true</tt>. If the validation results in a change in the field's validity, a
73      * {@link #validitychange} event will be fired. This allows the field to show feedback about the
74      * validity of its contents immediately as the user is typing.</p>
75      * <p>When set to <tt>false</tt>, feedback will not be immediate. However the form will still be validated
76      * before submitting if the <tt>clientValidation</tt> option to {@link Ext.form.Basic#doAction} is
77      * enabled, or if the field or form are validated manually.</p>
78      * <p>See also {@link Ext.form.field.Base#checkChangeEvents}for controlling how changes to the field's value are detected.</p>
79      */
80     validateOnChange: true,
81
82     /**
83      * @private
84      */
85     suspendCheckChange: 0,
86
87     /**
88      * Initializes this Field mixin on the current instance. Components using this mixin should call
89      * this method during their own initialization process.
90      */
91     initField: function() {
92         this.addEvents(
93             /**
94              * @event change
95              * Fires when a user-initiated change is detected in the value of the field.
96              * @param {Ext.form.field.Field} this
97              * @param {Mixed} newValue The new value
98              * @param {Mixed} oldValue The original value
99              */
100             'change',
101             /**
102              * @event validitychange
103              * Fires when a change in the field's validity is detected.
104              * @param {Ext.form.field.Field} this
105              * @param {Boolean} isValid Whether or not the field is now valid
106              */
107             'validitychange',
108             /**
109              * @event dirtychange
110              * Fires when a change in the field's {@link #isDirty} state is detected.
111              * @param {Ext.form.field.Field} this
112              * @param {Boolean} isDirty Whether or not the field is now dirty
113              */
114             'dirtychange'
115         );
116
117         this.initValue();
118     },
119
120     /**
121      * @protected
122      * Initializes the field's value based on the initial config.
123      */
124     initValue: function() {
125         var me = this;
126
127         /**
128          * @property originalValue
129          * @type Mixed
130          * The original value of the field as configured in the {@link #value} configuration, or as loaded by
131          * the last form load operation if the form's {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
132          * setting is <code>true</code>.
133          */
134         me.originalValue = me.lastValue = me.value;
135
136         // Set the initial value - prevent validation on initial set
137         me.suspendCheckChange++;
138         me.setValue(me.value);
139         me.suspendCheckChange--;
140     },
141
142     /**
143      * Returns the {@link Ext.form.field.Field#name name} attribute of the field. This is used as the parameter
144      * name when including the field value in a {@link Ext.form.Basic#submit form submit()}.
145      * @return {String} name The field {@link Ext.form.field.Field#name name}
146      */
147     getName: function() {
148         return this.name;
149     },
150
151     /**
152      * Returns the current data value of the field. The type of value returned is particular to the type of the
153      * particular field (e.g. a Date object for {@link Ext.form.field.Date}).
154      * @return {Mixed} value The field value
155      */
156     getValue: function() {
157         return this.value;
158     },
159     
160     /**
161      * Sets a data value into the field and runs the change detection and validation.
162      * @param {Mixed} value The value to set
163      * @return {Ext.form.field.Field} this
164      */
165     setValue: function(value) {
166         var me = this;
167         me.value = value;
168         me.checkChange();
169         return me;
170     },
171
172     /**
173      * Returns whether two field {@link #getValue values} are logically equal. Field implementations may override
174      * this to provide custom comparison logic appropriate for the particular field's data type.
175      * @param {Mixed} value1 The first value to compare
176      * @param {Mixed} value2 The second value to compare
177      * @return {Boolean} True if the values are equal, false if inequal.
178      */
179     isEqual: function(value1, value2) {
180         return String(value1) === String(value2);
181     },
182
183     /**
184      * <p>Returns the parameter(s) that would be included in a standard form submit for this field. Typically this
185      * will be an object with a single name-value pair, the name being this field's {@link #getName name} and the
186      * value being its current stringified value. More advanced field implementations may return more than one
187      * name-value pair.</p>
188      * <p>Note that the values returned from this method are not guaranteed to have been successfully
189      * {@link #validate validated}.</p>
190      * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array
191      * of strings if that particular name has multiple values. It can also return <tt>null</tt> if there are no
192      * parameters to be submitted.
193      */
194     getSubmitData: function() {
195         var me = this,
196             data = null;
197         if (!me.disabled && me.submitValue && !me.isFileUpload()) {
198             data = {};
199             data[me.getName()] = '' + me.getValue();
200         }
201         return data;
202     },
203
204     /**
205      * <p>Returns the value(s) that should be saved to the {@link Ext.data.Model} instance for this field, when
206      * {@link Ext.form.Basic#updateRecord} is called. Typically this will be an object with a single name-value
207      * pair, the name being this field's {@link #getName name} and the value being its current data value. More
208      * advanced field implementations may return more than one name-value pair. The returned values will be
209      * saved to the corresponding field names in the Model.</p>
210      * <p>Note that the values returned from this method are not guaranteed to have been successfully
211      * {@link #validate validated}.</p>
212      * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array
213      * of strings if that particular name has multiple values. It can also return <tt>null</tt> if there are no
214      * parameters to be submitted.
215      */
216     getModelData: function() {
217         var me = this,
218             data = null;
219         if (!me.disabled && !me.isFileUpload()) {
220             data = {};
221             data[me.getName()] = me.getValue();
222         }
223         return data;
224     },
225
226     /**
227      * Resets the current field value to the originally loaded value and clears any validation messages.
228      * See {@link Ext.form.Basic}.{@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
229      */
230     reset : function(){
231         var me = this;
232         
233         me.setValue(me.originalValue);
234         me.clearInvalid();
235         // delete here so we reset back to the original state
236         delete me.wasValid;
237     },
238
239     /**
240      * Resets the field's {@link #originalValue} property so it matches the current {@link #getValue value}.
241      * This is called by {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues} if the form's
242      * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} property is set to true.
243      */
244     resetOriginalValue: function() {
245         this.originalValue = this.getValue();
246         this.checkDirty();
247     },
248
249     /**
250      * <p>Checks whether the value of the field has changed since the last time it was checked. If the value
251      * has changed, it:</p>
252      * <ol>
253      * <li>Fires the {@link #change change event},</li>
254      * <li>Performs validation if the {@link #validateOnChange} config is enabled, firing the
255      * {@link #validationchange validationchange event} if the validity has changed, and</li>
256      * <li>Checks the {@link #isDirty dirty state} of the field and fires the {@link #dirtychange dirtychange event}
257      * if it has changed.</li>
258      * </ol>
259      */
260     checkChange: function() {
261         if (!this.suspendCheckChange) {
262             var me = this,
263                 newVal = me.getValue(),
264                 oldVal = me.lastValue;
265             if (!me.isEqual(newVal, oldVal) && !me.isDestroyed) {
266                 me.lastValue = newVal;
267                 me.fireEvent('change', me, newVal, oldVal);
268                 me.onChange(newVal, oldVal);
269             }
270         }
271     },
272
273     /**
274      * @private
275      * Called when the field's value changes. Performs validation if the {@link #validateOnChange}
276      * config is enabled, and invokes the dirty check.
277      */
278     onChange: function(newVal, oldVal) {
279         if (this.validateOnChange) {
280             this.validate();
281         }
282         this.checkDirty();
283     },
284
285     /**
286      * <p>Returns true if the value of this Field has been changed from its {@link #originalValue}.
287      * Will always return false if the field is disabled.</p>
288      * <p>Note that if the owning {@link Ext.form.Basic form} was configured with
289      * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
290      * then the {@link #originalValue} is updated when the values are loaded by
291      * {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues}.</p>
292      * @return {Boolean} True if this field has been changed from its original value (and
293      * is not disabled), false otherwise.
294      */
295     isDirty : function() {
296         var me = this;
297         return !me.disabled && !me.isEqual(me.getValue(), me.originalValue);
298     },
299
300     /**
301      * Checks the {@link #isDirty} state of the field and if it has changed since the last time
302      * it was checked, fires the {@link #dirtychange} event.
303      */
304     checkDirty: function() {
305         var me = this,
306             isDirty = me.isDirty();
307         if (isDirty !== me.wasDirty) {
308             me.fireEvent('dirtychange', me, isDirty);
309             me.onDirtyChange(isDirty);
310             me.wasDirty = isDirty;
311         }
312     },
313
314     /**
315      * @private Called when the field's dirty state changes.
316      * @param {Boolean} isDirty
317      */
318     onDirtyChange: Ext.emptyFn,
319
320     /**
321      * <p>Runs this field's validators and returns an array of error messages for any validation failures.
322      * This is called internally during validation and would not usually need to be used manually.</p>
323      * <p>Each subclass should override or augment the return value to provide their own errors.</p>
324      * @param {Mixed} value The value to get errors for (defaults to the current field value)
325      * @return {Array} All error messages for this field; an empty Array if none.
326      */
327     getErrors: function(value) {
328         return [];
329     },
330
331     /**
332      * <p>Returns whether or not the field value is currently valid by {@link #getErrors validating} the
333      * field's current value. The {@link #validitychange} event will not be fired; use {@link #validate}
334      * instead if you want the event to fire. <b>Note</b>: {@link #disabled} fields are always treated as valid.</p>
335      * <p>Implementations are encouraged to ensure that this method does not have side-effects such as
336      * triggering error message display.</p>
337      * @return {Boolean} True if the value is valid, else false
338      */
339     isValid : function() {
340         var me = this;
341         return me.disabled || Ext.isEmpty(me.getErrors());
342     },
343
344     /**
345      * <p>Returns whether or not the field value is currently valid by {@link #getErrors validating} the
346      * field's current value, and fires the {@link #validitychange} event if the field's validity has
347      * changed since the last validation. <b>Note</b>: {@link #disabled} fields are always treated as valid.</p>
348      * <p>Custom implementations of this method are allowed to have side-effects such as triggering error
349      * message display. To validate without side-effects, use {@link #isValid}.</p>
350      * @return {Boolean} True if the value is valid, else false
351      */
352     validate : function() {
353         var me = this,
354             isValid = me.isValid();
355         if (isValid !== me.wasValid) {
356             me.wasValid = isValid;
357             me.fireEvent('validitychange', me, isValid);
358         }
359         return isValid;
360     },
361
362     /**
363      * A utility for grouping a set of modifications which may trigger value changes into a single
364      * transaction, to prevent excessive firing of {@link #change} events. This is useful for instance
365      * if the field has sub-fields which are being updated as a group; you don't want the container
366      * field to check its own changed state for each subfield change.
367      * @param fn A function containing the transaction code
368      */
369     batchChanges: function(fn) {
370         this.suspendCheckChange++;
371         fn();
372         this.suspendCheckChange--;
373         this.checkChange();
374     },
375
376     /**
377      * Returns whether this Field is a file upload field; if it returns true, forms will use
378      * special techniques for {@link Ext.form.Basic#submit submitting the form} via AJAX. See
379      * {@link Ext.form.Basic#hasUpload} for details. If this returns true, the {@link #extractFileInput}
380      * method must also be implemented to return the corresponding file input element.
381      * @return {Boolean}
382      */
383     isFileUpload: function() {
384         return false;
385     },
386
387     /**
388      * Only relevant if the instance's {@link #isFileUpload} method returns true. Returns a reference
389      * to the file input DOM element holding the user's selected file. The input will be appended into
390      * the submission form and will not be returned, so this method should also create a replacement.
391      * @return {HTMLInputElement}
392      */
393     extractFileInput: function() {
394         return null;
395     },
396
397     /**
398      * <p>Associate one or more error messages with this field. Components using this mixin should implement
399      * this method to update the component's rendering to display the messages.</p>
400      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to
401      * return <code>false</code> if the value does <i>pass</i> validation. So simply marking a Field as invalid
402      * will not prevent submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation}
403      * option set.</p>
404      * @param {String/Array} errors The error message(s) for the field.
405      * @method
406      */
407     markInvalid: Ext.emptyFn,
408
409     /**
410      * <p>Clear any invalid styles/messages for this field. Components using this mixin should implement
411      * this method to update the components rendering to clear any existing messages.</p>
412      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to
413      * return <code>true</code> if the value does not <i>pass</i> validation. So simply clearing a field's errors
414      * will not necessarily allow submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation}
415      * option set.</p>
416      * @method
417      */
418     clearInvalid: Ext.emptyFn
419
420 });
421