Roo/form/Field.js
[roojs1] / Roo / form / Field.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.form.Field
14  * @extends Roo.BoxComponent
15  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16  * @constructor
17  * Creates a new Field
18  * @param {Object} config Configuration options
19  */
20 Roo.form.Field = function(config){
21     Roo.form.Field.superclass.constructor.call(this, config);
22 };
23
24 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
25     /**
26      * @cfg {String} fieldLabel Label to use when rendering a form.
27      */
28        /**
29      * @cfg {String} qtip Mouse over tip
30      */
31      
32     /**
33      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
34      */
35     invalidClass : "x-form-invalid",
36     /**
37      * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
38      */
39     invalidText : "The value in this field is invalid",
40     /**
41      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
42      */
43     focusClass : "x-form-focus",
44     /**
45      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
46       automatic validation (defaults to "keyup").
47      */
48     validationEvent : "keyup",
49     /**
50      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
51      */
52     validateOnBlur : true,
53     /**
54      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
55      */
56     validationDelay : 250,
57     /**
58      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
59      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
60      */
61     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
62     /**
63      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
64      */
65     fieldClass : "x-form-field",
66     /**
67      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
68      *<pre>
69 Value         Description
70 -----------   ----------------------------------------------------------------------
71 qtip          Display a quick tip when the user hovers over the field
72 title         Display a default browser title attribute popup
73 under         Add a block div beneath the field containing the error text
74 side          Add an error icon to the right of the field with a popup on hover
75 [element id]  Add the error text directly to the innerHTML of the specified element
76 </pre>
77      */
78     msgTarget : 'qtip',
79     /**
80      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
81      */
82     msgFx : 'normal',
83
84     /**
85      * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute.
86      */
87     readOnly : false,
88
89     /**
90      * @cfg {Boolean} disabled True to disable the field (defaults to false).
91      */
92     disabled : false,
93
94     /**
95      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
96      */
97     inputType : undefined,
98     
99     /**
100      * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
101          */
102         tabIndex : undefined,
103         
104     // private
105     isFormField : true,
106
107     // private
108     hasFocus : false,
109     /**
110      * @property {Roo.Element} fieldEl
111      * Element Containing the rendered Field (with label etc.)
112      */
113     /**
114      * @cfg {Mixed} value A value to initialize this field with.
115      */
116     value : undefined,
117
118     /**
119      * @cfg {String} name The field's HTML name attribute.
120      */
121     /**
122      * @cfg {String} cls A CSS class to apply to the field's underlying element.
123      */
124
125         // private ??
126         initComponent : function(){
127         Roo.form.Field.superclass.initComponent.call(this);
128         this.addEvents({
129             /**
130              * @event focus
131              * Fires when this field receives input focus.
132              * @param {Roo.form.Field} this
133              */
134             focus : true,
135             /**
136              * @event blur
137              * Fires when this field loses input focus.
138              * @param {Roo.form.Field} this
139              */
140             blur : true,
141             /**
142              * @event specialkey
143              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
144              * {@link Roo.EventObject#getKey} to determine which key was pressed.
145              * @param {Roo.form.Field} this
146              * @param {Roo.EventObject} e The event object
147              */
148             specialkey : true,
149             /**
150              * @event change
151              * Fires just before the field blurs if the field value has changed.
152              * @param {Roo.form.Field} this
153              * @param {Mixed} newValue The new value
154              * @param {Mixed} oldValue The original value
155              */
156             change : true,
157             /**
158              * @event invalid
159              * Fires after the field has been marked as invalid.
160              * @param {Roo.form.Field} this
161              * @param {String} msg The validation message
162              */
163             invalid : true,
164             /**
165              * @event valid
166              * Fires after the field has been validated with no errors.
167              * @param {Roo.form.Field} this
168              */
169             valid : true
170         });
171     },
172
173     /**
174      * Returns the name attribute of the field if available
175      * @return {String} name The field name
176      */
177     getName: function(){
178          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
179     },
180
181     // private
182     onRender : function(ct, position){
183         Roo.form.Field.superclass.onRender.call(this, ct, position);
184         if(!this.el){
185             var cfg = this.getAutoCreate();
186             if(!cfg.name){
187                 cfg.name = this.name || this.id;
188             }
189             if(this.inputType){
190                 cfg.type = this.inputType;
191             }
192             this.el = ct.createChild(cfg, position);
193         }
194         var type = this.el.dom.type;
195         if(type){
196             if(type == 'password'){
197                 type = 'text';
198             }
199             this.el.addClass('x-form-'+type);
200         }
201         if(this.readOnly){
202             this.el.dom.readOnly = true;
203         }
204         if(this.tabIndex !== undefined){
205             this.el.dom.setAttribute('tabIndex', this.tabIndex);
206         }
207
208         this.el.addClass([this.fieldClass, this.cls]);
209         this.initValue();
210     },
211
212     /**
213      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
214      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
215      * @return {Roo.form.Field} this
216      */
217     applyTo : function(target){
218         this.allowDomMove = false;
219         this.el = Roo.get(target);
220         this.render(this.el.dom.parentNode);
221         return this;
222     },
223
224     // private
225     initValue : function(){
226         if(this.value !== undefined){
227             this.setValue(this.value);
228         }else if(this.el.dom.value.length > 0){
229             this.setValue(this.el.dom.value);
230         }
231     },
232
233     /**
234      * Returns true if this field has been changed since it was originally loaded and is not disabled.
235      */
236     isDirty : function() {
237         if(this.disabled) {
238             return false;
239         }
240         return String(this.getValue()) !== String(this.originalValue);
241     },
242
243     // private
244     afterRender : function(){
245         Roo.form.Field.superclass.afterRender.call(this);
246         this.initEvents();
247     },
248
249     // private
250     fireKey : function(e){
251         //Roo.log('field ' + e.getKey());
252         this.fireEvent("keydown", this, e);
253         if(e.isNavKeyPress()){
254             this.fireEvent("specialkey", this, e);
255         }
256     },
257
258     /**
259      * Resets the current field value to the originally loaded value and clears any validation messages
260      */
261     reset : function(){
262         this.setValue(this.originalValue);
263         this.clearInvalid();
264     },
265
266     // private
267     initEvents : function(){
268         // safari killled keypress - so keydown is now used..
269         this.el.on("keydown" , this.fireKey,  this);
270         this.el.on("focus", this.onFocus,  this);
271         this.el.on("blur", this.onBlur,  this);
272
273         // reference to original value for reset
274         this.originalValue = this.getValue();
275     },
276
277     // private
278     onFocus : function(){
279         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
280             this.el.addClass(this.focusClass);
281         }
282         if(!this.hasFocus){
283             this.hasFocus = true;
284             this.startValue = this.getValue();
285             this.fireEvent("focus", this);
286         }
287     },
288
289     beforeBlur : Roo.emptyFn,
290
291     // private
292     onBlur : function(){
293         this.beforeBlur();
294         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
295             this.el.removeClass(this.focusClass);
296         }
297         this.hasFocus = false;
298         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
299             this.validate();
300         }
301         var v = this.getValue();
302         if(String(v) !== String(this.startValue)){
303             this.fireEvent('change', this, v, this.startValue);
304         }
305         this.fireEvent("blur", this);
306     },
307
308     /**
309      * Returns whether or not the field value is currently valid
310      * @param {Boolean} preventMark True to disable marking the field invalid
311      * @return {Boolean} True if the value is valid, else false
312      */
313     isValid : function(preventMark){
314         if(this.disabled){
315             return true;
316         }
317         var restore = this.preventMark;
318         this.preventMark = preventMark === true;
319         var v = this.validateValue(this.processValue(this.getRawValue()));
320         this.preventMark = restore;
321         return v;
322     },
323
324     /**
325      * Validates the field value
326      * @return {Boolean} True if the value is valid, else false
327      */
328     validate : function(){
329         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
330             this.clearInvalid();
331             return true;
332         }
333         return false;
334     },
335
336     processValue : function(value){
337         return value;
338     },
339
340     // private
341     // Subclasses should provide the validation implementation by overriding this
342     validateValue : function(value){
343         return true;
344     },
345
346     /**
347      * Mark this field as invalid
348      * @param {String} msg The validation message
349      */
350     markInvalid : function(msg){
351         if(!this.rendered || this.preventMark){ // not rendered
352             return;
353         }
354         this.el.addClass(this.invalidClass);
355         msg = msg || this.invalidText;
356         switch(this.msgTarget){
357             case 'qtip':
358                 this.el.dom.qtip = msg;
359                 this.el.dom.qclass = 'x-form-invalid-tip';
360                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
361                     Roo.QuickTips.enable();
362                 }
363                 break;
364             case 'title':
365                 this.el.dom.title = msg;
366                 break;
367             case 'under':
368                 if(!this.errorEl){
369                     var elp = this.el.findParent('.x-form-element', 5, true);
370                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
371                     this.errorEl.setWidth(elp.getWidth(true)-20);
372                 }
373                 this.errorEl.update(msg);
374                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
375                 break;
376             case 'side':
377                 if(!this.errorIcon){
378                     var elp = this.el.findParent('.x-form-element', 5, true);
379                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
380                 }
381                 this.alignErrorIcon();
382                 this.errorIcon.dom.qtip = msg;
383                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
384                 this.errorIcon.show();
385                 this.on('resize', this.alignErrorIcon, this);
386                 break;
387             default:
388                 var t = Roo.getDom(this.msgTarget);
389                 t.innerHTML = msg;
390                 t.style.display = this.msgDisplay;
391                 break;
392         }
393         this.fireEvent('invalid', this, msg);
394     },
395
396     // private
397     alignErrorIcon : function(){
398         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
399     },
400
401     /**
402      * Clear any invalid styles/messages for this field
403      */
404     clearInvalid : function(){
405         if(!this.rendered || this.preventMark){ // not rendered
406             return;
407         }
408         this.el.removeClass(this.invalidClass);
409         switch(this.msgTarget){
410             case 'qtip':
411                 this.el.dom.qtip = '';
412                 break;
413             case 'title':
414                 this.el.dom.title = '';
415                 break;
416             case 'under':
417                 if(this.errorEl){
418                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
419                 }
420                 break;
421             case 'side':
422                 if(this.errorIcon){
423                     this.errorIcon.dom.qtip = '';
424                     this.errorIcon.hide();
425                     this.un('resize', this.alignErrorIcon, this);
426                 }
427                 break;
428             default:
429                 var t = Roo.getDom(this.msgTarget);
430                 t.innerHTML = '';
431                 t.style.display = 'none';
432                 break;
433         }
434         this.fireEvent('valid', this);
435     },
436
437     /**
438      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
439      * @return {Mixed} value The field value
440      */
441     getRawValue : function(){
442         var v = this.el.getValue();
443         if(v === this.emptyText){
444             v = '';
445         }
446         return v;
447     },
448
449     /**
450      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
451      * @return {Mixed} value The field value
452      */
453     getValue : function(){
454         var v = this.el.getValue();
455         if(v === this.emptyText || v === undefined){
456             v = '';
457         }
458         return v;
459     },
460
461     /**
462      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
463      * @param {Mixed} value The value to set
464      */
465     setRawValue : function(v){
466         return this.el.dom.value = (v === null || v === undefined ? '' : v);
467     },
468
469     /**
470      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
471      * @param {Mixed} value The value to set
472      */
473     setValue : function(v){
474         this.value = v;
475         if(this.rendered){
476             this.el.dom.value = (v === null || v === undefined ? '' : v);
477             this.validate();
478         }
479     },
480
481     adjustSize : function(w, h){
482         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
483         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
484         return s;
485     },
486
487     adjustWidth : function(tag, w){
488         tag = tag.toLowerCase();
489         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
490             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
491                 if(tag == 'input'){
492                     return w + 2;
493                 }
494                 if(tag = 'textarea'){
495                     return w-2;
496                 }
497             }else if(Roo.isOpera){
498                 if(tag == 'input'){
499                     return w + 2;
500                 }
501                 if(tag = 'textarea'){
502                     return w-2;
503                 }
504             }
505         }
506         return w;
507     }
508 });
509
510
511 // anything other than normal should be considered experimental
512 Roo.form.Field.msgFx = {
513     normal : {
514         show: function(msgEl, f){
515             msgEl.setDisplayed('block');
516         },
517
518         hide : function(msgEl, f){
519             msgEl.setDisplayed(false).update('');
520         }
521     },
522
523     slide : {
524         show: function(msgEl, f){
525             msgEl.slideIn('t', {stopFx:true});
526         },
527
528         hide : function(msgEl, f){
529             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
530         }
531     },
532
533     slideRight : {
534         show: function(msgEl, f){
535             msgEl.fixDisplay();
536             msgEl.alignTo(f.el, 'tl-tr');
537             msgEl.slideIn('l', {stopFx:true});
538         },
539
540         hide : function(msgEl, f){
541             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
542         }
543     }
544 };