Roo/form/MonthField.js
[roojs1] / Roo / form / MonthField.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.MonthField
14  * @extends Roo.form.TriggerField
15  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
16 * @constructor
17 * Create a new MonthField
18 * @param {Object} config
19  */
20 Roo.form.MonthField = function(config){
21     
22     Roo.form.MonthField.superclass.constructor.call(this, config);
23     
24       this.addEvents({
25          
26         /**
27          * @event select
28          * Fires when a date is selected
29              * @param {Roo.form.MonthFieeld} combo This combo box
30              * @param {Date} date The date selected
31              */
32         'select' : true
33          
34     });
35     
36     
37     if(typeof this.minValue == "string") {
38         this.minValue = this.parseDate(this.minValue);
39     }
40     if(typeof this.maxValue == "string") {
41         this.maxValue = this.parseDate(this.maxValue);
42     }
43     this.ddMatch = null;
44     if(this.disabledDates){
45         var dd = this.disabledDates;
46         var re = "(?:";
47         for(var i = 0; i < dd.length; i++){
48             re += dd[i];
49             if(i != dd.length-1) re += "|";
50         }
51         this.ddMatch = new RegExp(re + ")");
52     }
53 };
54
55 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
56     /**
57      * @cfg {String} format
58      * The default date format string which can be overriden for localization support.  The format must be
59      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
60      */
61     format : "M Y",
62     /**
63      * @cfg {String} altFormats
64      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
65      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
66      */
67     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
68     /**
69      * @cfg {Array} disabledDays
70      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
71      */
72     disabledDays : [0,1,2,3,4,5,6],
73     /**
74      * @cfg {String} disabledDaysText
75      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
76      */
77     disabledDaysText : "Disabled",
78     /**
79      * @cfg {Array} disabledDates
80      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
81      * expression so they are very powerful. Some examples:
82      * <ul>
83      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
84      * <li>["03/08", "09/16"] would disable those days for every year</li>
85      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
86      * <li>["03/../2006"] would disable every day in March 2006</li>
87      * <li>["^03"] would disable every day in every March</li>
88      * </ul>
89      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
90      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
91      */
92     disabledDates : null,
93     /**
94      * @cfg {String} disabledDatesText
95      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
96      */
97     disabledDatesText : "Disabled",
98     /**
99      * @cfg {Date/String} minValue
100      * The minimum allowed date. Can be either a Javascript date object or a string date in a
101      * valid format (defaults to null).
102      */
103     minValue : null,
104     /**
105      * @cfg {Date/String} maxValue
106      * The maximum allowed date. Can be either a Javascript date object or a string date in a
107      * valid format (defaults to null).
108      */
109     maxValue : null,
110     /**
111      * @cfg {String} minText
112      * The error text to display when the date in the cell is before minValue (defaults to
113      * 'The date in this field must be after {minValue}').
114      */
115     minText : "The date in this field must be equal to or after {0}",
116     /**
117      * @cfg {String} maxTextf
118      * The error text to display when the date in the cell is after maxValue (defaults to
119      * 'The date in this field must be before {maxValue}').
120      */
121     maxText : "The date in this field must be equal to or before {0}",
122     /**
123      * @cfg {String} invalidText
124      * The error text to display when the date in the field is invalid (defaults to
125      * '{value} is not a valid date - it must be in the format {format}').
126      */
127     invalidText : "{0} is not a valid date - it must be in the format {1}",
128     /**
129      * @cfg {String} triggerClass
130      * An additional CSS class used to style the trigger button.  The trigger will always get the
131      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
132      * which displays a calendar icon).
133      */
134     triggerClass : 'x-form-date-trigger',
135     
136
137     /**
138      * @cfg {Boolean} useIso
139      * if enabled, then the date field will use a hidden field to store the 
140      * real value as iso formated date. default (true)
141      */ 
142     useIso : true,
143     /**
144      * @cfg {String/Object} autoCreate
145      * A DomHelper element spec, or true for a default element spec (defaults to
146      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
147      */ 
148     // private
149     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
150     
151     // private
152     hiddenField: false,
153     
154     hideMonthPicker : false,
155     
156     onRender : function(ct, position)
157     {
158         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
159         if (this.useIso) {
160             this.el.dom.removeAttribute('name'); 
161             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
162                     'before', true);
163             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
164             // prevent input submission
165             this.hiddenName = this.name;
166         }
167             
168             
169     },
170     
171     // private
172     validateValue : function(value)
173     {
174         value = this.formatDate(value);
175         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
176             return false;
177         }
178         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
179              return true;
180         }
181         var svalue = value;
182         value = this.parseDate(value);
183         if(!value){
184             this.markInvalid(String.format(this.invalidText, svalue, this.format));
185             return false;
186         }
187         var time = value.getTime();
188         if(this.minValue && time < this.minValue.getTime()){
189             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
190             return false;
191         }
192         if(this.maxValue && time > this.maxValue.getTime()){
193             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
194             return false;
195         }
196         /*if(this.disabledDays){
197             var day = value.getDay();
198             for(var i = 0; i < this.disabledDays.length; i++) {
199                 if(day === this.disabledDays[i]){
200                     this.markInvalid(this.disabledDaysText);
201                     return false;
202                 }
203             }
204         }
205         */
206         var fvalue = this.formatDate(value);
207         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
208             this.markInvalid(String.format(this.disabledDatesText, fvalue));
209             return false;
210         }
211         */
212         return true;
213     },
214
215     // private
216     // Provides logic to override the default TriggerField.validateBlur which just returns true
217     validateBlur : function(){
218         return !this.menu || !this.menu.isVisible();
219     },
220
221     /**
222      * Returns the current date value of the date field.
223      * @return {Date} The date value
224      */
225     getValue : function(){
226         
227         
228         
229         return  this.hiddenField ?
230                 this.hiddenField.value :
231                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
232     },
233
234     /**
235      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
236      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
237      * (the default format used is "m/d/y").
238      * <br />Usage:
239      * <pre><code>
240 //All of these calls set the same date value (May 4, 2006)
241
242 //Pass a date object:
243 var dt = new Date('5/4/06');
244 monthField.setValue(dt);
245
246 //Pass a date string (default format):
247 monthField.setValue('5/4/06');
248
249 //Pass a date string (custom format):
250 monthField.format = 'Y-m-d';
251 monthField.setValue('2006-5-4');
252 </code></pre>
253      * @param {String/Date} date The date or valid date string
254      */
255     setValue : function(date){
256         Roo.log('month setValue' + date);
257         // can only be first of month..
258         
259         var val = this.parseDate(date);
260         
261         if (this.hiddenField) {
262             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
263         }
264         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
265         this.value = this.parseDate(date);
266     },
267
268     // private
269     parseDate : function(value){
270         if(!value || value instanceof Date){
271             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
272             return value;
273         }
274         var v = Date.parseDate(value, this.format);
275         if (!v && this.useIso) {
276             v = Date.parseDate(value, 'Y-m-d');
277         }
278         if (v) {
279             // 
280             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
281         }
282         
283         
284         if(!v && this.altFormats){
285             if(!this.altFormatsArray){
286                 this.altFormatsArray = this.altFormats.split("|");
287             }
288             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
289                 v = Date.parseDate(value, this.altFormatsArray[i]);
290             }
291         }
292         return v;
293     },
294
295     // private
296     formatDate : function(date, fmt){
297         return (!date || !(date instanceof Date)) ?
298                date : date.dateFormat(fmt || this.format);
299     },
300
301     // private
302     menuListeners : {
303         select: function(m, d){
304             this.setValue(d);
305             this.fireEvent('select', this, d);
306         },
307         show : function(){ // retain focus styling
308             this.onFocus();
309         },
310         hide : function(){
311             this.focus.defer(10, this);
312             var ml = this.menuListeners;
313             this.menu.un("select", ml.select,  this);
314             this.menu.un("show", ml.show,  this);
315             this.menu.un("hide", ml.hide,  this);
316         }
317     },
318     // private
319     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
320     onTriggerClick : function(){
321         if(this.disabled){
322             return;
323         }
324         if(this.menu == null){
325             this.menu = new Roo.menu.DateMenu();
326            
327         }
328         
329         Roo.apply(this.menu.picker,  {
330             
331             showClear: this.allowBlank,
332             minDate : this.minValue,
333             maxDate : this.maxValue,
334             disabledDatesRE : this.ddMatch,
335             disabledDatesText : this.disabledDatesText,
336             
337             format : this.useIso ? 'Y-m-d' : this.format,
338             minText : String.format(this.minText, this.formatDate(this.minValue)),
339             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
340             
341         });
342          this.menu.on(Roo.apply({}, this.menuListeners, {
343             scope:this
344         }));
345        
346         
347         var m = this.menu;
348         var p = m.picker;
349         
350         // hide month picker get's called when we called by 'before hide';
351         
352         var ignorehide = true;
353         p.hideMonthPicker  = function(disableAnim){
354             if (ignorehide) {
355                 return;
356             }
357              if(this.monthPicker){
358                 Roo.log("hideMonthPicker called");
359                 if(disableAnim === true){
360                     this.monthPicker.hide();
361                 }else{
362                     this.monthPicker.slideOut('t', {duration:.2});
363                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
364                     p.fireEvent("select", this, this.value);
365                     m.hide();
366                 }
367             }
368         }
369         
370         Roo.log('picker set value');
371         Roo.log(this.getValue());
372         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
373         m.show(this.el, 'tl-bl?');
374         ignorehide  = false;
375         // this will trigger hideMonthPicker..
376         
377         
378         // hidden the day picker
379         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
380         
381         
382         
383       
384         
385         p.showMonthPicker.defer(100, p);
386     
387         
388        
389     },
390
391     beforeBlur : function(){
392         var v = this.parseDate(this.getRawValue());
393         if(v){
394             this.setValue(v);
395         }
396     }
397
398     /** @cfg {Boolean} grow @hide */
399     /** @cfg {Number} growMin @hide */
400     /** @cfg {Number} growMax @hide */
401     /**
402      * @hide
403      * @method autoSize
404      */
405 });