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