EXT Table Control 1 (updated on March 31, October 11, selected from "pay for learning Ext")

Source: Internet
Author: User

I. Rich Content and powerful functions

EXT is very powerful. It can be selected multiple times, highlighted, and so on. It can also automatically generate row numbers, support all checkbox selection, support local and remote paging, and render cells. You can even drag between the tree and grid.

2. Now let's design a grid.

1. Create a two-dimensional array to design a table.

In Ext, the column is defined as columnmodel, and CM is short for it. Here we create a table with three columns:

var cm = new Ext.grid.ColumnModel(    [           {header:"编号",dataIndex:"id"},           {header:"名称",dataIndex:"name"},           {header:"描述",dataIndex:"descn"}    ]);    

Specifically, header indicates the column name, And dataindex indicates the corresponding things.

 

2. This is just a skeleton. Now we want to add data to it. Of course, the data is also two-dimensional. Here we will directly write the data into Js.

var data = [      [‘1‘,‘name1‘,‘descn1‘],      [‘2‘,‘name2‘,‘descn2‘],      [‘3‘,‘name3‘,‘descn3‘],      [‘4‘,‘name4‘,‘descn4‘],      [‘5‘,‘name5‘,‘descn5‘]];

The two-dimensional array should contain five rows in the grid, with three columns in each row matching the ID, name, and descn. In order to turn imagination into reality, we also need to convert the original data.

3. How to convert: we need a bridge.

We hope that grid not only supports array, but also JSON and XML, and even supports our own data formats. EXT provides us with a bridge, ext. data. store, through which we can convert data in any format to a grid, so that you do not need to write a grid for each data format. Let's see how Ext. Data. Store converts array.

var ds = new Ext.data.Store(      proxy:new Ext.data.MemoryProxy(data),      reader:new Ext.data.ArrayReader({},[              {name:‘id‘},              {name:‘name‘},              {name:‘descn‘}        ]             )    );ds.load();

DS must correspond to two parts: proxy and reader. Proxy tells us where to get the data, and reader tells us to parse the data. Here we use Ext. Data. memoryproxy to parse JS variables. We passed it as a parameter. Ext. data. arrayreader is used to parse arrays and tells us that the tower will parse the data according to the defined specifications. It reads three data entries in each row, and the first data entry is "ID". Is it very familiar, it corresponds to the definition of cm, which corresponds to dataindex. This CM will know which column should display which data. Finally, another load () operation is executed to initialize the data.

Someone asked, what if the first column of data is not ID but name? You can use mapping to solve the problem.

var ds = new Ext.data.Store(      proxy:new Ext.data.MemoryProxy(data),      reader:new Ext.data.ArrayReader({},[              {name:‘id‘,mapping:1},              {name:‘name‘,mapping:0},              {name:‘descn‘,mapping:3}        ]             )    );

The data in the ID and name columns is flipped, and the mapping index starts from 0.

4. We need to assemble.

 
var grid = new Ext.grid.Grid("grid",{      ds:ds,      cm:cm});
grid.render();

Note: The header is ext = 1. write method of X, ext. grid. the first parameter of grid is the rendering ID, which corresponds to a <Div id = 'grid'> </div> in HTML so that grid knows where to draw itself.

After creating a grid, you must use the grid. Render () method to render the grid.

Put all the code in one piece:

var cm = new Ext.grid.ColumnModel(    [           {header:"编号",dataIndex:"id"},           {header:"名称",dataIndex:"name"},           {header:"描述",dataIndex:"descn"}    ]);    

var data = [      [‘1‘,‘name1‘,‘descn1‘],      [‘2‘,‘name2‘,‘descn2‘],      [‘3‘,‘name3‘,‘descn3‘],      [‘4‘,‘name4‘,‘descn4‘],      [‘5‘,‘name5‘,‘descn5‘]];
 
var ds = new Ext.data.Store(      proxy:new Ext.data.MemoryProxy(data),      reader:new Ext.data.ArrayReader({},[              {name:‘id‘,mapping:1},              {name:‘name‘,mapping:0},              {name:‘descn‘,mapping:3}        ]             )    );
var grid = new Ext.grid.Grid("grid",{      ds:ds,      cm:cm});
grid.render();
 

The result is:

 

Iii. Differences in ext2.0

First, ext. Grid. Grid is missing. We need to use Ext. Grid. gridpanel. The parameters to be passed are also different.

var grid = new Ext.grid.GridPanel(  {      el:‘grid‘,      ds:ds,      cm:cm    }  );

The ID of the rendering location is put in {}, and the corresponding name is El.

Secondly, CSS is different for less than 2.0 of your "zebra crossings. By default, both versions of grid can drag and drop columns or change the width.

Iv. Common functions

1. Determine the width of each column

CM supports setting the width of each column. If you do not set the width, it will take a default value. The default value is 100.

var cm = new Ext.grid.ColumnModel([          {header:"编号",dataIndex:"id",width:20}]);

For automatic filling, version 1.0 is:

var grid = new Ext.grid.Grid(   "grid",   {ds:ds,     cm:cm,     autoSizeColumns:true  });

In version 2.0, forefit in viewconfig is used.

var grid = new Ext.grid.GridPanel([           el:"grid",           ds:ds,           cm:cm,           viewConfig:{                      forceFit:true               } ]);

If you specify a column for automatic filling, you can do this in version 1.0:

Add one more parameter to grid. Grid: autoexpandcolunm: "ID of the specified column"

2. Let grid support column-based sorting: At the header where grid. columnmodel needs to be sorted by column, followed:

Sortable: True.

3. Renderer rendering function: achieves different font colors of a column.

var cm = new Ext.grid.ColumnModel([      {header:‘编号‘,dataIndex:"id"},      {header:"性别",dataIndex:"sex",renderer:function(value){         if(value==‘male‘){          return "<span style=‘color:red;font-weigh:bold;‘>红男</span>          return "<span style=‘color:green;font-weigh:bold;‘>绿女</span>
        }, ////省略部分代码  
} ]);

Here we change the male color to red, and the female color to Red. The parameter value is the text to change the color. You will be followed by an image link to make the table content more lively.

Here, we also want to introduce the number of parameters in a render:

Value refers to the value of the current cell.

Cellmeta stores the cellid Cell ID, which should be the column number.

Record is all the data in this row. You can use record. Data ['id'] to obtain the desired data.

Rowindex is the row number, not from the beginning to the bottom, it is the result after the page

Columnindex column number

Store is the ds that you pass when constructing a table. That is to say, it is all the data in the table and can be called at will.

 

4. What we need is the time format.

When we need time format, write the corresponding type and dateformat In the data. Store () data source;

var ds = new Ext.data.Store( proxy:new Ext.data.MemoryProxy(data), reader:new Ext.data.ArrayReader(           {},          [            {name:‘id‘},            {name:‘name‘},            {name:‘descn‘},            {name:‘data‘,type:‘date‘,dataFormat:‘Y-m-dTH:i:s‘}                    ]           ) );

 

Step 2: In cm, we can write like this:

{header:‘日期‘,dataIndex:"data",type:‘data‘,renderer:Ext.util.Format.dateRenderer(‘Y年m月d日‘)}

You can see that the corresponding value is Y, M, and D, corresponding to the dateformat format.

 

5. Automatic row number and multiple checkbox Selection

1. In fact, multiple checkbox and row numbers are extensions of Renderer, which are often used together. The statement for automatic row number is to add in cm

new Ext.grid.RowNumerer(),

How to delete a row? In HTML, write a button with the ID of remove. In this example, delete the message in the second line. You can call grid. View. Refresh () to refresh the form so that the row number is continuous.

Ext.get(‘remove‘).on(     ‘click‘,     function(){         ds.remove(ds.getAt(1));
grid.view.refresh(); });

2. Select All functions

First read the table

What is more?

var sm = new Ext.grid.CheckboxSelectionModel(handleMouseDown:Ext.emptyFn);

This all-selected SM has two positions: one is added to cm and the other is added to Ext. Grid. gridpanel. (Note: In this example, ext. emptyfn does not select the checkbox option when selecting a row, but does not select the row when selecting the checkbox option ).

6. Paging

Paging is a very important feature, because you may process thousands of data records, and they cannot appear in the same page.

The grid integration page is divided into two steps.

1. Get the paging Toolbar

The Code is as follows:

var gridFoot = grid.getView().getFooterPanel(true);var paging = new Ext.PagingToolbar(    gridFoot,ds,    {         pageSize:10,         displayInfo:true,         displayMsg:‘显示第{0}到{1}条记录,一共{2}条‘,         emptyMsg:‘没有记录‘     } );

First use grid. getview (). getfootpanel (true) to obtain the bottom of the grid.

Let's take a look at the parameters:

Pagesize indicates the number of data entries displayed on each page.

Displayinfo is related to the following configuration. If it is false, no prompt is displayed.

Displaymsg is valid in displayinfo: True. It is used to display the prompt information when data is available.

Emptymsg displays this if there is no data.

In version 2.0, it is much easier.

Add the following directly in Ext. Grid. gridpanel:

bbar:new Ext.PagingToolbar(........)

If it is at the top

tbar:new Ext.PagingToolbar()

 

VII. editorgrid

1. To make the unit editable text, add the following content to the header of CM:

editor:new Ext.grid.GridEditor(           new Ext.form.TextField({                allowBlank:false                }))

The editing text is textfield and cannot be blank. By default, this editor is activated when you double-click it. You can also write clickstoedit: 1 in grid. editorgrid to change it to a click event.

2. add and delete a row.

First, we create a record.

var Record = Ext.data.Record.create([ {name:‘id‘,type:‘string‘}, {name:‘name‘,type:‘string‘}, {name:‘descn‘,type:‘string‘}]);

Now we add two buttons, one for adding rows, the other for deleting rows, and temporarily placing them in the grid header.

var gridHead = grid.getView().getHeaderPanel(true);var tb = new Ext.Toolbar(      gridHead,[‘-‘,{       text:‘添加一行‘,       handler:function(){                   var initValue ={id:‘‘,name:‘‘,descn:‘‘};                   var p =new Record(initValue);                   grid.stopEditing();                   ds.insert(0,p);                   grid.startEditing(0,0);                   p.dirty = true;                   p.modifued = initValue;                   if(ds.modified.indexOf(p) == -1) {                       ds.modified.push(p);                              }                  },              ‘-‘     {      text:‘删除一行‘,      handler:function(){               Ext.Msg.confirm(                      ‘信息‘,‘确定要删除?‘,                       function(btn){                       if(btn == ‘yes‘){                               var sm = grid.getSelectionModel();                               var cell = sm.getSelectedCell();                               var record = ds.getAt(cell[0]);                               ds.remove(record);                                   }                               }                         );                    }               }          },‘-‘]);

We define a record, assign a value to it, disable the table editing status (grid. stopediting (), and insert the first row of DS. Startingediting () activates the editing status in the first column of the first row, prompting you to write data. The dirty and modifed operations are for good looks. The grid will display some of the data.

The Delete row button finds the record corresponding to the DS row through the row number, and then deletes it.

 

EXT Table Control 1 (updated on March 31, October 11, selected from "pay for learning Ext")

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.