How to implement Dynamic patchwork DataGrid tables with Easyui+java

Source: Internet
Author: User
Tags one table

Let's take a look at the effect, and we've been studying this thing for a while.

What if I choose to widen the date interval? Like May to May 5? Let's look at the results below, don't worry about it!

See, Haha, this date is generated dynamically, the following to share with you this method of implementation.

I was implemented in the background of Java EE,

First to paste the HTML code:

1 <div> site: <input class= "Easyui-combobox" width= "200px" id= "Stnmcombo" >&nbsp; 2 start time: <input id= "StartTime" class= "Easyui-datebox"  editable= "false"/> 3 &nbsp; End time: <input id= " EndTime "class=" Easyui-datebox "editable=" false "/> 4 <a id=" btnsearch "href=" # "class=" Easyui-linkbutton " data-options= "Iconcls: ' Icon-search '" > Query </a> &nbsp; 5 <a id= "Export" href= "#" class= "Easyui-linkbutton" data-options= "iconcls: ' Icon-search '" > Export </a>  6 </div> 7  8 <div class= "Easyui-layout" fit= "true" > 9     <table id= "DG" ></table>10 </ Div>
View Code

HTML code is very simple, in which the key DataGrid has only one table, in fact, the key lies in the JS code OH

The following code is sent out:

Let me explain to you the next few key areas and ideas, the code is not particularly complex.

    1. Formloader.load (Param1,param2,function (s) {}) The first parameter of this method is the name of the controller's requestmapping, as it is done with the MVC three-layer architecture, The second argument can be a string or a JSON object, and this method returns a JSON object, and if alert (s) sees the result, a method of the company framework, so you don't have to look for it, I just share the idea.
    2. This example is the background structure of dynamic columns, using more than the push method, using the push method to store the JSON object into the array.

Here are a few things to explain: Table header name Title,field (the corresponding key returned by the JSON object), field give you a picture to know

Here is the specific code:

var gv=$ ("#dg"); var today=new Date ();//dynamically generated column Var Dynamiccols=[];var dynamicitems=[];var Dynamicitemsafter=[];var dynamicitemsend=[];$ (function () {$ ("#StartTime"). Datebox (' SetValue ', today.getfullyear () + "-" + (Today.getmonth () +1    ) + "-" + (Today.getdate ()-1));        $ ("#EndTime"). Datebox (' SetValue ', today.getfullyear () + "-" + (Today.getmonth () +1) + "-" + (Today.getdate ()));                Bind null Data Gv.datagrid ("DataBind", {autoheight:46, datas: [],    Striped:true, Pagination:true, autorowheight:false}); Bind empty column Gv.datagrid ({columns:[[{title: ' Time ', width:150,sortable:true}, {titl E: ' Site 1 ', width:150,sortable:true}, {title: ' Site 2 ', width:150,sortable:true}, {title: ' Site 3 ', WI    (Dth:500,sortable:true},]]});          });//Column element (dynamic)//serial number var stcd={field: ' Stcd ', title: ' Serial Number ',width:150, Rowspan:3, sortable:true}//station name var stnm={field: ' Stnm ', title: ' Station name ',// width:150, Rowspan:3, sortable:true}//average var avg={title: ' Average ',//width:500, Colspan:2} Reservoir water level var rz={title: ' Reservoir water level ',//width:150/*ps: Dynamic column is not suitable for fixed width, other same */}//capacity var rv={title: ' Storage capacity ', width:150}//Library        Tolerance (average) var rvavg={title: ' Storage capacity ', field: ' RvAvg2 ',//width:500 formatter:function (Value,row,index)        {return "-"; }}//Query button $ ("#btnSearch"). Click (function () {//Gets the difference in the number of days between the start date and the end date var ipt1=$ ("#StartTime"). Datebox (' Getvalu    E ');        var ipt2=$ ("#EndTime"). Datebox (' GetValue ');     var arr1 = Ipt1.split ("-");         var arr2 = Ipt2.split ("-");     var dt1 = new Date ();     Dt1.setfullyear (Arr1[0]);     Dt1.setmonth (Arr1[1]-1);      Dt1.setdate (arr1[2]);     var dt2 = new Date ();      Dt2.setfullyear (Arr2[0]);     Dt2.setmonth (Arr2[1]-1);  Dt2.setdate (arr2[2]);    var dif = Dt2.gettime ()-dt1.gettime ();                 var days = dif/(24 * 60 * 60 * 1000);     Initialize again to avoid the stacking of arrays dynamiccols=[];     Dynamicitems=[];     Dynamicitemsafter=[];        Dynamicitemsend=[];    Front Dynamicitems.push (STCD);    Dynamicitems.push (STNM); Query condition data var datas={"STCD": $ ("#stnmCombo"). ComboBox (' GetValue '), "StartTime": $ ("#StartTime"). dat Ebox (' GetValue '), "EndTime": $ ("#EndTime"). Datebox (' GetValue ')}//Query specific data form                Loader.load ("Querydata", datas,function (s) {//blank span var blank={title: ',        Colspan:days*2+4//Dynamically get colspan span, depending on the number of days} dynamicitems.push (blank);        var sss = s;            Traverse dynamic Array//for (j=0;j<s.length;j++)//{//alert (s.daynamiclist[1].z0); Alert (s[7).                DYNAMICLIST.Z0); Dynamically loading incoming water level data//library water level rz={title: ' Reservoir water level ', field: "Dynamiclist", Formatter:function (Value,row,index) {//alert (row); return VALUE.Z1;                Because this is an object dynamiclist, the value of the returned object is//alert (value);                var temp;                        $.each (Value,function (i,option) {//alert (option);                    Temp=option;                                });            return temp;           }}//alert (s); Patchwork Table Head $.each (S[0].                   Dynamiclist, Function (i,option) {//alert (i);                    alert (i); rv={title: ' Storage capacity ', field: ' DynamicList2 ', fo                            Rmatter:function (value,row,index) {return "-";                   }                                                                            }                 Detailed data var k=0;                                      Set a value to match z0,z1,z2 .....                   var d = new Date ($ ("#StartTime"). Datebox (' GetValue '));                       do{//alert (i.substring (1)); D.setdate (D.getdate () +parseint (i.substring (1))); Convert to type int var realdate=d.getfullyear () + "-" + (D.getmonth () +1) + "-" +d.getdate () ;                       Dynamically get Date value var details2={title:realdate,                                              width:150, Colspan:2}                      Dynamicitemsafter.push (DETAILS2);                      k+=2; Break This is because I will execute this result, so break off}while (days>k)//dyn                   Amicitemsafter.push (DETAILS2); DYnamicitemsend.push (RZ);//Dynamicitemsend.push (RV);                   Dynamicitemsend.push (RZ);                                          Dynamicitemsend.push (RV);                                                  Dynamicitemsafter.push (DETAILS2);            });  }//Library water level (average) var rzavg={title: ' Reservoir water level ', field: ' DynamicList5 ', Here is a random field formatter:function (value,row,index) {var k=row.                   Dynamiclist;                   Alert (k);                   Calculate the mean Var temp=0;                       $.each (K,function (i,option) {//alert (option);                       alert (i);                       Temp+=number (option);                   Alert (temp);                   });                   Alert (temp);                   return 0;                                      Alert (temp); Return temp/(DAYS+1); }//width:150}//alert (S[0].            STCD);            Dynamicitemsafter.push (avg);            Dynamicitemsend.push (RZAVG);                    Dynamicitemsend.push (RVAVG);        Dynamiccols.push (Dynamicitems);        Dynamiccols.push (Dynamicitemsafter);        Dynamiccols.push (Dynamicitemsend);                                  Bind dynamic Column Gv.datagrid ({columns:dynamiccols,}); Gv.datagrid ("DataBind", {datas:s, strip                                                        Ed:true, Pagination:true, pagesize:15        });            Total ();        });    });//Get station code var datacount=0;formloader.load ("Getstnm", "", function (data) {Data.unshift ({stnm: "All", Stcd: "}"); $ ("#stnmCombo"). ComboBox ({data:data, Valuefield: "Stcd", TEXtfield: "Stnm", Editable:false,//panelheight: "Auto", Onloadsuccess:function () {            Alert (' 1 '); Alert (data[0).            STCD); $ ("#stnmCombo"). ComboBox (' SetValue ', data[0].            STCD);                Datacount=data.length; }, Onshowpanel:function () {if (datacount.length>10) {$ (this). Combob                            Ox (' panel '). Height (251); }                        }    });});

The difficulty of this example is to build a dynamic DTO entity class, because I return a list<dto name, because the column is not fixed, so this is a difficult point, how to implement it?

In fact, we have carefully noticed that there is a field called dynamiclist we put this dynamiclist open to look inside the internal structure.

This is actually because I chose 8 date intervals, so there are 8 elements in it, if I choose 4 days time interval?

How does this come true?

The following into the background time, in fact, the background is splicing SQL, first of all to see how the query SQL is pieced together.

Public String querysql (reservoirdayreportparam param) {stringbuffer sb=new stringbuffer ();                Sb.append ("Select B.stnm,r.stcd,");        Start time and end time String starttime=param.getstarttime ();                String Endtime=param.getendtime ();        SimpleDateFormat format =new simpledateformat ("Yyyy-mm-dd");        Calendar start=calendar.getinstance ();        Calendar end=calendar.getinstance ();            try {start.settime (Format.parse (startTime));        End.settime (Format.parse (endTime));        } catch (Exception e) {e.printstacktrace ();        }//Traverse out time int count=0; while (Start.compareto (end) <=0) {String Time=format.format (Start.gettime ()            );    String finalstart=time.concat ("00:00:00"); The final daily start time of the String finalend=time.concat ("23:59:59"); End-of-day Sb.append ("Max" (Case time R.tm beTween ' "+finalstart+" ' and ' "+finalend+" ' then R.rz else 0 end "as Z" +count+ ",");             count++;            Start.add (Calendar.day_of_month, 1); The alias of the column} String tempbuffer=sb.substring (0,sb.length ()-1); Remove the last comma of the obtained value StringBuffer lastbuff=new stringbuffer ();                        Create a new string Lastbuff.append (Tempbuffer);        Lastbuff.append ("from St_rsvr_r r,st_stbprp_b B where R.stcd=b.stcd");        if (!param.getstcd (). Equals ("")) {Lastbuff.append ("and r.stcd= '" +PARAM.GETSTCD () + "'");        } lastbuff.append ("Group by B.stnm,r.stcd");    return lastbuff.tostring ();     }
The Reservoirdayreportparam is an entity class, the code has comments, I say the key, in fact, the dynamic column (water level) This column, in fact, according to the start time and end time, to loop to put together the SQL, the code is not too difficult, A count variable is used in the middle to alias the column, such as z0,z1,z2,z3 ... Wait a minute.

Then this realizes the dynamic splicing SQL, that is, I have chosen how many date interval, will be in the background as how many dynamic columns, the following first look at the entity model it.

    Start time and end time    private String startTime;    Private String endTime;        Public  Map getdynamiclist () {        return dynamiclist;    }    public void Setdynamiclist (Map  dynamiclist) {        this.dynamiclist = dynamiclist;    }    Dynamic entity class    private Map dynamiclist;

The dynamiclist is dynamic, why is the map type? That's because you can add key-value pairs. Add the shape like Z0,Z1 to the inside, which makes the dynamic.

The beginning has already said the Formloader method, then we want to execute this method, in the background advantage what?

Public list<reservoirdayreportparam> querydata (reservoirdayreportparam param) {//TODO auto-generated method         Stub String sql=querysql (param);        list<object[]> datafromstcd=this.daohelper.findbysql (SQL);        List<reservoirdayreportparam> arrlist=new arraylist<reservoirdayreportparam> ();        List List = new ArrayList (); try {for (object[] obj:datafromstcd) {Reservoirdayreportparam params=new Reservoirdayrepo            Rtparam (); Map map=new Linkedhashmap ();            Create a new arrlist for storing dynamic column params.setstnm (string.valueof (obj[0));                        Params.setstcd (string.valueof (obj[1));                Save the dynamic column to the map and set the key value pair for the for (int i=2;i<datafromstcd.get (0). length;i++) {            Map.put ("Z" + (i-2), obj[i]);            } params.setdynamiclist (map);        Arrlist.add (params);          }      } catch (Exception e) {e.printstacktrace ();            } return arrlist; }


One of the querysql is just the method of splicing SQL.
First get the concatenation of SQL, the Findbysql method is to return a list of the methods of the collection, the company framework, know the meaning of the line, we can ignore.
The idea is to loop the results from the list and add them to the entity class, then add each entity class to the ArrayList and then return.

How to implement Dynamic patchwork DataGrid tables with Easyui+java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.