ExtJs只给我们提供了日历插件,可以显示各种格式的年月日,可是有时候,项目只要求显示年月即可,比如管理系统中我要查看某人从1月份到3月份的考勤情况。月份控件定义如下:
Ext.define('Ext.form.field.Month', {
extend: 'Ext.form.field.Date',
alias: 'widget.monthfield',
requires: ['Ext.picker.Month'],
alternateClassName: ['Ext.form.MonthField', 'Ext.form.Month'],
selectMonth: null,
createPicker: function () {
var me = this,
format = Ext.String.format;
return Ext.create('Ext.picker.Month', {
pickerField: me,
ownerCt: me.ownerCt,
renderTo: document.body,
floating: true,
hidden: true,
focusOnShow: true,
minDate: me.minValue,
maxDate: me.maxValue,
disabledDatesRE: me.disabledDatesRE,
disabledDatesText: me.disabledDatesText,
disabledDays: me.disabledDays,
disabledDaysText: me.disabledDaysText,
format: me.format,
showToday: me.showToday,
startDay: me.startDay,
minText: format(me.minText, me.formatDate(me.minValue)),
maxText: format(me.maxText, me.formatDate(me.maxValue)),
listeners: {
select: {scope: me, fn: me.onSelect},
monthdblclick: {scope: me, fn: me.onOKClick},
yeardblclick: {scope: me, fn: me.onOKClick},
OkClick: {scope: me, fn: me.onOKClick},
CancelClick: {scope: me, fn: me.onCancelClick}
},
keyNavConfig: {
esc: function () {
me.collapse();
}
}
});
},
onCancelClick: function () {
var me = this;
me.selectMonth = null;
me.collapse();
},
onOKClick: function () {
var me = this;
if (me.selectMonth) {
me.setValue(me.selectMonth);
me.fireEvent('select', me, me.selectMonth);
}
me.collapse();
},
onSelect: function (m, d) {
var me = this;
me.selectMonth = new Date((d[0] + 1) + '/1/' + d[1]);
}
});
使用的时候很简单,和datefield使用方法一样的,引入monthfield,添加format: 'Y-m'即可,其它属性和datefield通用
{
xtype: 'monthfield',
submitFormat: 'Y-m-d',
format: 'Y-m'
}
控件使用起来虽然简单,但有个小小的问题,就是在表单提交的时候,获取的不是Y-m格式的值,而且Y-m-d的值,通过dom获取的是Y-m格式的值,这不影响我们的项目,如果是通过表单提交的,在后台获取参数的时候subString(0, 7)就好了。测试用例如下:
Ext.create('Ext.form.Panel', {
title: 'Test form',
margin: 10,
width: 300,
renderTo: Ext.getBody(),
items: [{
xtype: 'monthfield',
submitFormat: 'Y-m-d',
id: 'txMonth',
name: 'month',
fieldLabel: '月份',
format: 'Y-m'
}, {
xtype: 'datefield',
submitFormat: 'Y-m-d',
name: 'date',
fieldLabel: '日期',
format: 'Y-m-d'
}],
buttons: [{
text: 'dom直接获取',
handler: function () {
Ext.Msg.alert('提示', Ext.getCmp('txMonth').getRawValue());
}
}, {
text: '表单获取参数',
handler: function () {
Ext.Msg.alert('提示', this.up('form').getForm().getValues(true));
}
}]
});
代码运行后,效果图如下:
点击dom按钮,弹出
点击表单按钮,弹出
大家在使用的时候稍微注意下就好了。