最近公司有个需求,需要根据检查单,获取数据列表,再将数据列横向排布作为grid的列,即动态列。
思路:Exjts的gridpanel有个方法grid.reconfigure(store, json.fieldheader),我们可以通过这个方法传递column和store,而store必须有data和fields,所以我们的目的是从后台获取三个对象:1、fields 2、data 3、header(表头)
思路有了,那就看如何实现,后台代码我已经把备注都写了,自己看
/**
* @功能描述:动态列
*/
public ActionForward getDynamicColumn(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/json;charset=utf-8");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,
new JsonDateValueProcessor());
Session session = null;
Transaction tx = null;
String checkNameId=request.getParameter("checkNameId"); //检查名称id
try {
session = HibernateClass.getSession();
tx = session.beginTransaction();
Query sq=session.createSQLQuery("select distinct t1.checksubitem from t_pm_projectcheck t,t_pm_projecteval t1 where t.id=t1.parentid and t.checknameid='"+checkNameId+"'");
List queryList=sq.list();
/*思路:1、获取表头*/
String[] header=getHeader(checkNameId,queryList);
/*如果表头个数不大于4(即扣除行号、项目名称、项目经理、总分4列),则返回空*/
if(header.length>4){
/*2、获取store的field内容*/
String[] fieldsInArray=getFieldsInArray(checkNameId,queryList);
/*3、获取store的data内容,即数据*/
String[][] content = this.getTableContent(checkNameId,queryList,session,header.length,fieldsInArray);
/*4、将content组装成json数据*/
String[] dataString=getContentStr(checkNameId,queryList,content,fieldsInArray);
/*5、利用JSONArray将数据装成Object传递到前台*/
JSONArray jsonObject = JSONArray.fromObject(header, jsonConfig);
String fieldheader = jsonObject.toString();
JSONArray jsonObject1 = JSONArray.fromObject(fieldsInArray, jsonConfig);
String fieldsInArraystr = jsonObject1.toString();
JSONArray jsonObject2= JSONArray.fromObject(dataString, jsonConfig);
String dataStringstr = jsonObject2.toString();
response.getWriter().write("{success:true,fieldheader:"+fieldheader+",fields:"+fieldsInArraystr+",contentstr:"+dataStringstr+"}");
}else{
response.getWriter().write("{success:true,msg:'NN'}");
}
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
response.getWriter().write("{success:0}");
} finally {
HibernateClass.closeSession(session);
}
return null;
}
/**
* 获取header
* @param checkNameId 检查名称Id
* @return
*/
public String[] getHeader(String checkNameId,List queryList){
String[] header=new String[queryList.size() + 4];
if(queryList.size()>0){
header[0]="{text : '序号', xtype:'rownumberer',width : 30,align : 'center'}";
header[1]="{text:'工程名称',dataIndex:'projectName',flex:2,align : 'center'}";
header[2]="{text:'项目经理',dataIndex:'projectManager',flex:1,align : 'center'}";
for(int i=0;i<queryList.size();i++){
String subitem=queryList.get(i).toString();
String temp="{text:'#1',dataIndex:'#2',flex:1,align : 'center'}";
String eres = new CnToEnglish().getSpell(subitem, true);
header[i+3]= temp.replace("#1", queryList.get(i).toString()).replace("#2", eres);
}
header[queryList.size() + 3]="{text:'合计总分',dataIndex:'totalCount',flex:1,align : 'center'}";
}
return header;
}
/**
* 获取字段
* @param checkNameId 检查名称Id
* @return
*/
public String[] getFieldsInArray(String checkNameId,List queryList){
String[] fields=new String[queryList.size() + 3];;
fields[0]="projectName";
fields[1]="projectManager";
if(queryList.size()>0){
for(int i=0;i<queryList.size();i++){
/*将中文表头格式化为英文首字母,用于dataIndex和store的field字段*/
String eres = new CnToEnglish().getSpell(queryList.get(i).toString(), true);
fields[i+2]=eres;
}
fields[queryList.size() + 2]="totalCount";
}
return fields;
}
/*将content组装为json格式*/
public String[] getContentStr(String checkNameId,List queryList,String[][] content ,String[] fields) {
String jsonContent[] = new String[content.length];
for (int i = 0; i < content.length; i++) {
String temp = "";
for (int j = 0; j < fields.length; j++) {
temp = temp + "'" + fields[j] + "':'" + content[i][j] + "',";
}
temp = "{" + temp.substring(0, temp.length() - 1) + "}";
jsonContent[i] = temp;
}
return jsonContent;
}
/*获取数据内容,组装成二维数组*/
public String[][] getTableContent(String checkNameId,List queryList,Session session,int headerLength,String[] fieldsInArray){
String[][] content=null;
/*1、获取工程名称、项目经理和总分*/
List queryOrg= session.createQuery("select distinct projectName,manager,checkScore from ProjectCheck where checkNameId=:checkNameId")
.setParameter("checkNameId", checkNameId).list();
/*2、二维数组 区间【项目总数】【表头总数】,备注:对于数据而言,首列不是行号列,而直接是数据列*/
content=new String[queryOrg.size()][headerLength];
/*3、遍历工程名称列表,即生成记录数*/
for(int i=0;i<queryOrg.size();i++){
Object[] obj=(Object[])queryOrg.get(i);
String projectName=obj[0].toString();
String manager=obj[1].toString();
content[i][0]=projectName;
content[i][1]=manager;
if(queryList.size()>0){
/*4、遍历subitem,即生成记录数*/
for(int j=0;j<queryList.size();j++){
String subitem=queryList.get(j).toString();
/*5、根据subitem、projectName、checkNameId,得到具体的actualScore*/
List scoreList= session.createQuery("select t.actualScore from ProjectEval t ,ProjectCheck t1 where t.parentId=t1.id " +
"and t1.checkNameId=:checkNameId and t1.projectName=:projectName and t.checkSubItem=:checkSubItem")
.setParameter("checkNameId", checkNameId).setParameter("projectName", projectName).setParameter("checkSubItem", subitem).list();
Object object = scoreList.get(0);
String actualScore = object == null ? "0.0" : object.toString();
content[i][j + 2] = actualScore;
}
}else{
/*6、如果queryList为空,则将subitem和总分都设置为0*/
if(headerLength>3){
for(int j=3;j<headerLength;j++){
content[i][j]="0.0";
}
}
}
/*7、设置总分*/
content[i][queryList.size() + 2]=obj[2].toString();
}
return content;
}
下面是前台关键代码
onStoreSelect : function(combo, records, options) {
var field=combo.up('toolbar').down('textfield[name=checkNameId]');
var checkNameId=records[0].data.id;
field.setValue(checkNameId);
var grid=combo.up('grid');
Ext.Ajax.request({
url : '../ProjectEval.do?method=getDynamicColumn',
params : {
checkNameId : checkNameId
},
method : 'POST',
success : function(response, options) {
var json = Ext.JSON.decode(response.responseText);
if(json.msg=='NN'){
var store = Ext.create('Ext.data.Store', {
fields : [],
data : []
});
store.load();
var array=new Array();
grid.reconfigure(store, array);
grid.body.dom.style.background="url(../images/norecord.jpg) repeat " ;
}else{
var contentstr=json.contentstr;
var store = Ext.create('Ext.data.Store', {
fields : json.fields,
data : contentstr
});
store.load();
grid.reconfigure(store, json.fieldheader);
grid.body.dom.style.background="" ;
}
}
});
},
最后的效果图