A tutorial on tables in the ExtJS framework of JavaScript _extjs

Source: Internet
Author: User
Tags extend json locale first row

Introduction to the characteristics of tables in ExtJS
the table is defined by the class Ext.grid.GridPanel and inherits from Ext.panel,xtype to Grid
Table column information is defined by Ext.grid.ColumnModel
The data memory of the table is defined by Ext.data.Store, and according to the different data, the data memory can be divided into the following kinds:

Jsonstore,simplestore,groupingstore ...

The basic process of writing a table:

1. Create a table column model

var cm = new Ext.grid.ColumnModel ({
 {header: ' Roles ', Dataindex: ' Role '},
 {header: ' Rank ', Dataindex: ' Grade '},
 { Header: ' Creation Date ', Dataindex: ' CreateDate ', type: ' Date ', renderer:Ext.util.Format.dateRenderer (' Y-year m-month d ')}//create date type data
});

2. Create an array of data

var data = [
  [' Soldier ', ' 7 ', ' 2011-07-2412:34:56 '],
  [' General ', ' ten ', ' 2011-07-2412:34:56 '],
];

3, create a data storage object store, contains two parts: proxy, the way to obtain data; reader, how to parse data

Arrayreader mapping is used to set the order of columns

var store = new Ext.data.Store ({
  proxy:new Ext.data.MemoryProxy (data),
  reader:new Ext.data.ArrayReader ({}, C3/>{name: ' Role ', mapping:1},
    {name: ' Grade ', mapping:0}
    {name: ' CreateDate ', mapping:2, type: ' Date ', datefor Mat: ' Y-m-dh:i:s '}//create date column and display format
  ]
});
Store.load ();

4. Create Gridpanel, assemble Columnmodel and store

var Grid = new Ext.grid.GridPanel ({
 renderto: ' Grid ',
 store:store,
 cm:cm
});

Additional remote data can be obtained using Scripttagproxy, as shown below

var store = new Ext.data.Store ({
  proxy:new Ext.data.ScriptTagProxy ({
   URL: ' http://... '}),
  reader:new Ext.data.ArrayReader ({}, [
    {name: ' Role ', mapping:1},
    {name: ' Grade ', mapping:0}
  ]),
  sortinfo: { Field: "Role", Direction: "ASC"}//set default row sequence, Asc/desc
});


Common property functions for tables

var Grid = new Ext.grid.GridPanel ({
 enablecolumnmove:false,//Disable drag and drop column
 Enablecolumnresize:false,//Disable column width change)
 striperows:true,//Zebra effect
 loadmask:true,//The Mask and hint function when reading data
 Renderto: ' Grid ',
 store:store
 cm:cm
});

var cm = new Ext.grid.ColumnModel ({
 {header: ' Roles ', Dataindex: ' Role ', width:90, sortable:true},//width set column width, defaults to 100 Px,sortable Set sort function
 {id: ' Grade ', Header: ' Rank ', Dataindex: ' Grade ', width:40}
});
var Grid = new Ext.grid.GridPanel ({
 renderto: ' Grid ',
 store:store,
 cm:cm
 viewconfig:{  // Let each column fill in the form
 forcefit:true
 }
 autoexpandcolumn: ' Grade '//automatically extend the column, the column ID in Columnmodel defined
});

Render a table and set a special style for a table
just add a renderer attribute to cm, adding a custom function to render the style of the parameters that are passed in (automatically delivered by EXT), that is, to assemble the corresponding HTML and CSS or JS response events before returning value.

function Rendersex (value) {
  if (value = = ' Male ') {return
    "<span style= ' color:blue; > Male </span>;
  } else {return
    "<span style= ' color:red;" > Female </span> ';
  }

var cm = new Ext.grid.ColumnModel ([
  {header: ' id ', dataindex: ' ID '},
  {header: ' name ', Dataindex: ' Name '},
  { Header: ' Sex ', dataindex: ' Sex ', renderer:rendersex},
];

var data = [
  [' 1 ', ' Jason ', ' Male '],
  [' 2 ', ' Kate ', ' female ']]
;

var store = new Ext.data.Store ({
  proxy:new Ext.data.MemoryProxy (data),
  reader:new Ext.data.ArrayReader ({}, [
    {name: ' ID '},
    {name: ' name '},
    {name: ' Sex '}
  ]
});
Store.load ();

var Grid = new Ext.grid.GridPanel ({
  autoheight:true,
  renderto: ' Grid ',
  store:store,
  cm:cm
});

Automatically displays line numbers, as long as you create a rownumberer when you create cm.

var cm = new Ext.grid.ColumnModel ([
 New Ext.grid.RowNumberer (),  ///Show line number
  {header: ' id ', dataindex: ' ID '},
  {header: ' name ', Dataindex: ' Name '},
  {header: ' Sex ', dataindex: ' Sex ', renderer:rendersex},
]);

Delete Column

Store.remove (Store.getat (i));

Refresh Table

Grid.view.refresh ();

Add a check box to a table
need to use Checkboxselectionmodel
Selectionmodel SM to be placed in cm and table when used

var sm = new Ext.grid.CheckboxSelectionModel ();

var cm = new Ext.grid.ColumnModel ([
  New Ext.grid.RowNumberer (),
  sm,
  {header: ' number ', Dataindex: ' ID '},
  { Header: ' names ', Dataindex: ' Name '}
];

var data = [
  [' 1 ', ' name1 '],
  [' 2 ', ' name2 ']]
;

var store = new Ext.data.Store ({
  proxy:new Ext.data.MemoryProxy (data),
  reader:new Ext.data.ArrayReader ({}, [
    {name: ' ID '},
    {name: ' name '}
  ]

});
Store.load ();

var Grid = new Ext.grid.GridPanel ({
  autoheight:true,
  renderto: ' Grid ',
  store:store,
  cm:cm,
  sm:sm
});

Select only one row through the Rowselectionmodel setting:

var Grid = new Ext.grid.GridPanel ({
  autoheight:true,
  renderto: ' Grid ',
  store:store,
  cm:cm,
  sm:new Ext.grid.RowSelectionModel ({singleselect:true})
});

Using the selection model to get the data

Grid.on (' click ', Function () {
  var selections = Grid.getselectionmodel (). Getselections ();
  for (var i = 0; i < selections.length. i++) {
    var record = selections[i];
    Ext.Msg.alert (Record.get ("id");
  }
);

Table View
look at the form control from the idea of MVC:
* Ext.data.Store can be considered as a model
* Ext.grid.GridPanel can be considered as a controller
* Ext.grid.GridView can be viewed as a view
* The general GridView is automatically generated by Gridpanell, and if you want to set the properties of the GridView, you can get the view instance through Ext.grid.GridPanel's GetView ()

Ext.get (' button1 '). On (' click ', Function () {
 grid.getview (). Scrolltotop ();
  Grid.getview (). Focuscell (0, 0);
  var cell = Grid.getview (). Getcell (0, 0);
  Cell.style.backgroundColor = ' red ';
};

Use Gridpanel Viewconfig to set initialization parameters for the GridView when creating a table

var Grid = new Ext.grid.GridPanel ({
  height:100,
  width:400,
  renderto: ' Grid ',
  store:new Ext.data.Store ({
    autoload:true,
    proxy:new Ext.data.MemoryProxy (data),
    reader:new Ext.data.ArrayReader ({}, meta)
  }),
  Columns:meta,
  viewconfig: {
    columnstext: ' Displayed columns ',//Set Drop-down menu Prompt text
    scrolloffset:30,  //Set the reserved width of the right scroll bar
    sortasctext: ' Ascending ',  //Setting Drop-down menu Prompt text
    sortdesctext: ' Descending ',  //Set Drop-down menu prompt text
    forcefit:true  //automatically extend the length of each column
  }
});

Add a pagination toolbar to a table
* You can use the Gridpanel Bbar property and create a Ext.pagingtoolbar page bar object
* Note that if the paging toolbar is configured, Store.load () must be executed after the table is constructed.

var Grid = new Ext.grid.GridPanel ({
  renderto: ' Grid ',
  autoheight:true,
  store:store,
  cm:cm,
  Bbar : New Ext.pagingtoolbar ({
    pagesize:10,  //per page display 10 data
    Store:store,
    displayinfo:true,  //Display data information
    displaymsg: ' Show {0} to {1} records, total {2} ',
    emptymsg: "No Record"  //No data displayed when information
  }
)});
Store.load ();

Getting paging data from a background script

Use Httpproxy to pass the request, get the server's JSON data, and give Jsonreader parsing

var cm = new Ext.grid.ColumnModel ([
  {header: ' numbered ', dataindex: ' ID '},
  {header: ' name ', Dataindex: ' names '}
]);
var store = new Ext.data.Store ({
  proxy:new Ext.data.HttpProxy ({url: ' page.jsp '}),
  reader:new Ext.data.JsonReader ({
    totalproperty: ' Totalproperty ',
    root: ' Root '
  }, [
    {name: ' ID '},
    {name: ' Name '}
  ]
});
var Grid = new Ext.grid.GridPanel ({
  renderto: ' Grid ',
  autoheight:true,  ///data is highly unknown before it is sent back, so use adaptive height
  Store:store,
  cm:cm,
  bbar:new ext.pagingtoolbar ({
    pagesize:10,
    Store:store,
    Displayinfo:true,
    displaymsg: ' Show {0} to {1} Records/Total {2} ',
    emptymsg: "No Record"
  })
});
Store.load ({params:{start:0,limit:10}});

If you want the page bar to appear at the top of the table, you can use the Gridpanel Tbar property settings to add a toolbar

Allow ExtJS to page through the returned data

* need to introduce the Pagingmemoryproxy.js file in the Examples/locale directory on the page
* Then use Pagingmemoryproxy to set up the agent

var store = new Ext.data.Store ({
  proxy:new Ext.data.PagingMemoryProxy (data),
  reader:new Ext.data.ArrayReader ({}, [
    {name: ' ID '},
    {name: ' name '},
    {name: ' DESCN '}
  ]
});
Call
store.load ({Params:{start:0,limit:3}}) after Gridpanel is created;

Use of editable Table control Editorgrid

To make a simple Editorgrid step:

1, define column Columnmodel, add editor attribute inside

var cm = new Ext.grid.ColumnModel ([{
  header: ' Numbered ',
  dataindex: ' id ',
  editor:new Ext.grid.GridEditor (
    New Ext.form.TextField ({
      allowblank:false//not allowed to enter null value in TextField
    })
}, {
  header: ' Name ',
  dataindex: ' name ',
  editor:new Ext.grid.GridEditor (
    new Ext.form.TextField ({
      Allowblank: False})))
;

2. Prepare an array

var data = [
  [' 1 ', ' Jason '],
  [' 2 ', ' Jay ']]
;

3, create Ext.data.Store, set up memory agent, set Arrayreader parse array

var store = new Ext.data.Store ({
  proxy:new Ext.data.MemoryProxy (data),
  reader:new Ext.data.ArrayReader ({}, C3/>{name: ' ID '},
    {name: ' name '}
  ]
};

4, load data, create Editorgridpanel

Store.load ();
var Grid = new Ext.grid.EditorGridPanel ({
  autoheight:true,
  renderto: ' Grid ',
  store:store,
  cm:cm
});

Add and delete data for an editable table

1. Create a recordset by using the record's Create method Myrecord,myrecord equivalent to a class

var Myrecord = Ext.data.Record.create ([
  {name: ' id ', type: ' String '},
  {name: ' name ', type: ' String '}
]);
store.load ();

2, create the Editorgridpanel panel, create the Ext.toolbar in the property Tbar

var Grid = new Ext.grid.EditorGridPanel ({
  autoheight:true,
  renderto: ' Grid ',
  store:store,
  cm:cm,
  tbar:new Ext.toolbar (['-', {//-= Menu separator
    text: ' Add row ',
    handler:function () {
      var p = new Myrecord ({
        ID: ',
        name: '
      };
      Grid.stopediting (); Closes the edit state of the table
      store.insert (0, p);//The record created is inserted into the first line of the store
      grid.startediting (0, 0);//Activate Edit status of first column in first row
  }, '-', {
    text: ' Delete Row ',
    handler:function () {
      Ext.Msg.confirm (' info ', ' OK to delete? ', function (BTN) {
        if (btn = = ' yes ') {
          var sm = Grid.getselectionmodel ();//Get Table selection model
          var cell = Sm.getselec Tedcell ();  Gets the selected cell
          var record = Store.getat (cell[0]);//The corresponding record Store.remove (record) of the store is obtained by line number
          ;  Remove Data
        }}
      ;}}
  , '-']
};

Save modified results for an editable table

On the basis of the above example, add a Save button

Text: ' Save ', handler:function () {var m = store.modified.slice (0);//Get Modified data in store for (var i = 0; i < m.length i
    + +) {//Verify that the form information is correct and contains a space var record = m[i];

    var fields = Record.fields.keys;
      for (var j = 0; J < Fields.length; J + +) {var name = Fields[j];

      var value = Record.data[name];
      var colindex = cm.findcolumnindex (name);
      var rowIndex = Store.indexofid (record.id);

      var editor = Cm.getcelleditor (colindex). field; if (!editor.validatevalue (value)) {Ext.Msg.alert (' hint ', ' please check that the data entered is correct!)
        ', function () {grid.startediting (RowIndex, Colindex);
        });
      Return
  }} var jsonarray = [];

  Ext.each (m, function (item) {Jsonarray.push (item.data);//Put the modified data into Jsonarray}); Ext.lib.Ajax.request (////using Ajax request submitted to backend ' POST ', ' save_data.jsp ', {success:function (response) {//return successful EXT .
      Msg.alert (' Information ', Response.responsetext, function () {store.reload ();
    }); },faiLure:function () {//Return failed Ext.Msg.alert ("error", "Server saves data Error!")
    ");
}, ' Data= ' + encodeuricomponent (Ext.encode (Jsonarray));

 }

In addition, the store can set property prunemodifiedrecords:true. In this way, the store automatically clears the modified tag each time the Remove or load operation is made, avoiding the occurrence of the last time the modified information will be brought with the next submission.


limit the data type entered by the table

Numberfield

{
  header: ' id ',
  dataindex: ' id ',
  editor:new Ext.grid.GridEditor (new Ext.form.NumberField ({// Numberfield limit can only be entered digital
    Allowblank:false,
    allownegative:false,//cannot enter minus
    maxvalue:10
  })
}

ComboBox

var combodata = [
  [' 0 ', ' Java '],
  [' 1 ', ' Android ']
];
{
  header: ' ComboBox ',
  dataindex: ' Combo ',
  editor:new Ext.grid.GridEditor (new Ext.form.ComboBox ({
    Store:new Ext.data.SimpleStore ({
      fields:[' value ', ' text '],
      data:combodata
    }),
    emptytext: ' Please choose ' ,
    mode: ' Local ',
    triggeraction: ' All ',
    Valuefield: ' Value ',
    displayfield: ' Text '
    , Readonly:true
  })),
  renderer:function (value) {return
    combodata[value][1];
  }
}

Datefield

{
  header: ' Date ',
  dataindex: ' Date ',
  editor:new Ext.grid.GridEditor (new Ext.form.DateField ({
    Format: ' y-m-d ',
    minvalue: ' 2011-07-24 ',
    disableddays: [0, 6],
    disableddaystext: ' Choose the date between Monday and Saturday '
  }),
  renderer:function (value) {return
    Value.format ("y-m-d");
  }
}

Use of Property Table control PropertyGrid
is a more intelligent advanced table component developed on the basis of Editorgrid

var Grid = new Ext.grid.PropertyGrid ({
  title: ' Property Table Control PropertyGrid ',
  autoheight:true,
  width:400,
  Renderto: ' Grid ',
  viewconfig: {
    forcefit:true
  },
  Source: {
    "string": "string",
    "Date": New Date (Date.parse (' 07/24/2011 ')),
    "Boolean": false,
    "float":.
  }
});

Ways to disable the PropertyGrid editing feature

Grid.on (' Beforeedit ', function (e) {
 e.cancel = true;
 return false;
});

Get value based on the name of the table

Grid.store.getById (' Jason '). get (value);


Implementing nested tables in ExtJS
First Look at the effect:

The code is as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

The "rowexpander.js" used in the ExtJS is included in the official example.

To implement this nested form, note two tips:
1. The datastore data source provided to the outer table represents the data for the detail area as a nested array, as shown in the following bold.

var testdata=[
  ["Lugreen", "Male", 26,[["mathematics", 100],["language", "the"]]]
  , ["Lisi", "male", "25,[[", "Mathematics", 100],["Chinese",
  )]] , ["Zhangsan", "Male", 27,[["mathematics", 120],["language", 158]]]  
;

Use the JSON attribute of the Record object in the array set to get the detail area data

var data=r.json[3];

2. Add nested tables in the Rowexpander expand event.

Related Article

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.