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