codeigniter集成jqgrid

openkk 12年前

/**  *第一步:加载helper  */  $this->load->helper('grid_helper');  $this->load->helper('url_helper');

//第二步:初始化表格参数  $aData = array(  'set_columns' => array(  array(  'label' => 'Customer ID',  'name' => 'custid',  'width' => 100,  'size' => 10  ),  array(  'label' => 'Customer Name',  'name' => 'custname',  'width' => 220,  'size' => 10  ),  array(  'label' => 'Status',  'name' => 'custstatus',  'width' => 100,  'size' => 10  )  ),  'div_name' => 'grid',  'source' => 'customer/customerList/',  'sort_name' => 'custname',  'add_url' => 'customer/exec/add',  'edit_url' => 'customer/exec/edit',  'delete_url' => 'customer/exec/del',  'caption' => 'Customer Maintenance',  'primary_key' => 'custid',  'grid_height' => 230  );

  • 其中各参数的含义为:
  • set_columns:

    表格中的列 (可以通过修改 grid_helper.php增加更多的列选项).
    div_name: div id where the jqgrid would be rendered.

  • source: The url parameter where the data would be fetched (I will tell you the contents of /customer/customerlist/ later).
  • sort_name: The column name that is sorted by default.
  • delete_url, add_url, edit_url: is the the jquery would redirect when editing,adding or deleting a record.
  • caption: Caption in the grid’s title bar.
  • primary_key: The primary key in your grid, this key would be passed when you are editing or deleting a record when the appropriate action button is pressed.
  • grid_height: set the height of the grid.
我们需要在控制器中构造一个函数用于取回数据.例如:  /customer/customerlist/. 获取客户列表的代码如下:
buildGridData(  array(  'model' => 'customer_model',  'method' => 'getAllCustomers',  'pkid' => 'custid',  'columns' => array( 'custid','custname','custstatus' )  )  );

我使用在grid_helper.php中定义的buildGridData函数,你只需要指定model名字,model的方法,如:

function getAllCustomers($paramArr) {  $start = isset($paramArr['start'])?$paramArr['start']:NULL;  $limit = isset($paramArr['limit'])?$paramArr['start']:NULL;  $sortField = isset($paramArr['sortField'])?$paramArr['sortField']:'custname';  $sortOrder = isset($paramArr['sortOrder'])?$paramArr['sortOrder']:'asc';  $whereParam = isset($paramArr['whereParam'])?$paramArr['whereParam']:NULL;  if(!empty($start) && !empty($limit)) $optLimit = "limit $start,$limit";  else $optLimit = NULL;    if(!empty($whereParam)) $whereParam = "and (".$whereParam.")";  $whereClause = "where true ".$whereParam;    $SQL = "SELECT * FROM tblcustomer $whereClause order by $sortField $sortOrder $optLimit ";  $result = $this->db->query($SQL);    if($result->num_rows() > 0) {  $custlist = $result->result();  return $custlist;  } else {  return null;  }  }

现在可以构造表格并在视图中加载它:

$data['customerGrid'] = buildGrid($aData);  $this->load->view( 'customer/customerlist',$data );

现在你只需要在视图中打印customerGrid.不要忘记增加一个表格其 id=”grid” ,增加一个 div,其id=”pager”。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml">  <head>  <title>JqGrid Demo</title>  <link rel="stylesheet" type="text/css" href="/css/ui.jqgrid.css" />  <link type="text/css" rel="stylesheet" href="/css/jquery-ui-1.8.12.custom.css" />  <script type="text/javascript" src="/js/jquery-1.5.2.min.js"></script>  <script type="text/javascript" src="/js/jquery-ui-1.8.12.custom.min.js"></script>  <script type="text/javascript" src="/js/jqgrid/grid.locale-en.js"></script>  <script type="text/javascript" src="/js/jqgrid/jquery.jqGrid.src.js"></script>  </head>  <body>  <table id="grid"></table>  <div id="pager"></div>  <?php echo $customerGrid; ?>  </body>  </html>

至此,所有工作已经完毕!

附: library 和 helper代码

<?php  /*@Developer  - Mark Lenard M. Mirandilla  *@Version 1.0  *@Description jqgrid library for Codeigniter  */  class JqGrid {  private $divName;  private $sourceUrl;  private $colNames;  private $colModels;  private $sortName;  private $caption;  private $gridHeight;  private $addUrl;  private $editUrl;  private $deleteUrl;  private $customButtons;  private $customFunctions;  private $subgrid;  private $subGridUrl;  private $subGridColumnNames;  private $subGridColumnWidth;    public function setColumns($columns) {  $tmpColNames = array();  $tmpColModels = '';    foreach ($columns as $columnNames => $columnOptions) {  foreach ($columnOptions as $columnName => $columnOption) {  $tmpColNames[] = $columnName;  $tmpColModels .= json_encode($columnOption).",";  }  }  $this->colNames = json_encode($tmpColNames);  $this->colModels = '['.$tmpColModels.']';  }    public function setDivName($divName) {  $this->divName = $divName;  }    public function setSourceUrl($url) {  $this->sourceUrl = $url;  }    public function setSortName($sortName) {  $this->sortName = $sortName;  }    public function setCaption($caption) {  $this->caption = $caption;  }    public function setGridHeight($height) {  $this->gridHeight = $height;  }    public function setPrimaryKey($primaryKey) {  $this->primaryKey = $primaryKey;  }    public function setAddUrl($url) {  $this->addUrl = $url;  }    public function setEditUrl($url) {  $this->editUrl = $url;  }    public function setDeleteUrl($url) {  $this->deleteUrl = $url;  }    public function setCustomButtons($buttons) {  $this->customButtons = $buttons;  }    public function setCustomFunctions($customFunctions) {  $this->customFunctions = $customFunctions;  }    public function setSubGrid($isSubGrid = FALSE) {  $this->subGrid = $isSubGrid;  }    public function setSubGridUrl($subGridUrl) {  $this->subGridUrl = $subGridUrl;  }    public function setSubGridColumnNames($columnNames) {  $this->subGridColumnNames = $columnNames;  }    public function setSubGridColumnWidth($columnWidth) {  $this->subGridColumnWidth = $columnWidth;  }    public function buildGrid() {  $buildDivName = $this->divName;  $buildSourceUrl = $this->sourceUrl;  $buildColNames = $this->colNames;  $buildColModels = $this->colModels;  $buildSortName = $this->sortName;  $buildEditUrl = $this->editUrl;  $buildAddUrl = $this->addUrl;  $buildDeleteUrl = $this->deleteUrl;  $buildCaption = $this->caption;  $buildGridHeight = $this->gridHeight;  $buildPrimaryKey = $this->primaryKey;  $buildCustomButtons = $this->customButtons;  $buildSubGrid = $this->subgrid;  $buildSubGridUrl = $this->subGridUrl;  $buildSubGridColumnNames = $this->subGridColumnNames;  $buildSubGridColumnWidth = $this->subGridColumnWidth;    $grid = "<script type='text/javascript'>";  $grid .= "$('#$buildDivName').jqGrid({  url:'$buildSourceUrl',  datatype: 'json',  colNames:$buildColNames,  colModel:$buildColModels,  rowNum:20,  rowList:[10,20,30],  pager: '#pager',  toppager:true,  cloneToTop:true,  sortname: '$buildSortName',  viewrecords: true,  sortorder: 'asc',  caption:'$buildCaption'";  $grid .= "});";    //NavBar  $grid .= "$('#$buildDivName').jqGrid('navGrid','#pager',  {search:true,edit:false,add:false,del:false,cloneToTop:true}, //options  {} // search options  )";  if( !empty( $buildCustomButtons ) ){  foreach($buildCustomButtons as $customButton) {  $customButton = ".navButtonAdd('#grid_toppager_left',".$customButton.")";  $grid .= $customButton;  }  }    $grid .= ".navButtonAdd('#grid_toppager_left',  { caption:'', buttonicon:'ui-icon-trash', onClickButton:jqGridDelete ,title: 'Delete selected row', position: 'first', cursor: 'pointer'})  .navButtonAdd('#grid_toppager_left',  { caption:'', buttonicon:'ui-icon-pencil', onClickButton:jqGridEdit,title: 'Edit selected row', position: 'first', cursor: 'pointer'})  .navButtonAdd('#grid_toppager_left',  { caption:'', buttonicon:'ui-icon-plus', onClickButton:jqGridAdd,title: 'Add new record', position: 'first', cursor: 'pointer'});";    $grid .= "  function jqGridAdd() {  location.href='$buildAddUrl?oper=add';  }    function jqGridEdit() {  var grid = $('#$buildDivName');  var sel_id = grid.jqGrid('getGridParam', 'selrow');  var myCellData = grid.jqGrid('getCell', sel_id, '$buildPrimaryKey');  if(!myCellData) {  alert('No selected row');  } else {  //alert(myCellData);    location.href='$buildEditUrl' + myCellData;  }  }    function jqGridDelete() {  var grid = $('#$buildDivName');  var sel_id = grid.jqGrid('getGridParam', 'selrow');  var recid = grid.jqGrid('getCell', sel_id, '$buildPrimaryKey');  if(!recid) {  alert('No selected row');  } else {  var ans = confirm('Delete selected record?');  if(ans) {  var data = {};  data.recid = recid;  $.post('$buildDeleteUrl',data);  $('#$buildDivName').trigger('reloadGrid');  }  }  }    ";  if( !empty( $this->customFunctions ) ){  foreach($this->customFunctions as $customFunction) {  $grid .= $customFunction;  }  }    //Set Grid Height  $grid .= "$('#$buildDivName').setGridHeight($buildGridHeight,true);";  $grid .= "$('.ui-jqgrid-titlebar-close','#gview_$buildDivName').remove();";  $grid .= "</script>";  return $grid;  }  }

<?php  function buildGrid( $aData ){  $CI =& get_instance();  $CI->load->library('JqGrid');  $jqGrid = $CI->jqgrid;  if( isset( $aData['set_columns'] ) ){  $aProperty = array();  foreach( $aData['set_columns'] as $sProperty ){  $aProperty[] = array(  $sProperty['label'] =>  array(  'name' => $sProperty['name'],  'index' => $sProperty['name'],  'width' => $sProperty['width'],  'editable' => false,  'editoptions' => array(  'readonly'=>'true',  'size'=> $sProperty['size']  )  )  );  }  $jqGrid->setColumns( $aProperty );  }    if( isset( $aData['custom'] ) ){  if( isset( $aData['custom']['button'] ) ){  $jqGrid->setCustomButtons( array( $aData['custom']['button'] ) );  }  if( isset( $aData['custom']['function'] ) ){  $jqGrid->setCustomFunctions( array( $aData['custom']['function'] ) );  }  }    if( isset( $aData['div_name'] ) ){  $jqGrid->setDivName( $aData['div_name'] );  } else {  $jqGrid->setDivName( 'grid' );  }    if( isset( $aData['source'] ) ) $jqGrid->setSourceUrl( base_url() . $aData['source'] );    if( isset( $aData['sort_name'] ) ) $jqGrid->setSortName( $aData['sort_name'] );    if( isset( $aData['add_url'] ) ) $jqGrid->setAddUrl( base_url() . $aData['add_url'] );    if( isset( $aData['delete_url'] ) ) $jqGrid->setDeleteUrl( base_url() . $aData['delete_url'] );    if( isset( $aData['edit_url'] ) ) $jqGrid->setEditUrl( base_url() . $aData['edit_url'] );    if( isset( $aData['caption'] ) ) $jqGrid->setCaption( $aData['caption'] );    if( isset( $aData['primary_key'] ) ) $jqGrid->setPrimaryKey( $aData['primary_key'] );    if( isset( $aData['grid_height'] ) ) $jqGrid->setGridHeight( $aData['grid_height'] );    if( isset( $aData['subgrid'] ) ) $jqGrid->setSubGrid($aData['subgrid']);    if( isset( $aData['subgrid_url'] ) ) $jqGrid->setSubGridUrl($aData['subgrid_url']);    if( isset( $aData['subgrid_columnnames'] ) ) $jqGrid->setSubGridColumnNames($aData['subgrid_columnnames']);    if( isset( $aData['subgrid_columnwidth'] ) ) $jqGrid->subGridColumnWidth($aData['subgrid_columnwidth']);    return $jqGrid->buildGrid();  }    function buildGridData( $aData ){  $CI =& get_instance();    $isSearch = $CI->input->get('_search');  $searchField = $CI->input->get('searchField');  $searchString = $CI->input->get('searchString');  $searchOperator = $CI->input->get('searchOper');  $page = $CI->input->get('page'); // get the requested page  $limit = $CI->input->get('rows'); // get how many rows we want to have into the grid  $sidx = $CI->input->get('sidx'); // get index row - i.e. user click to sort  $sord = $CI->input->get('sord'); // get the direction    if($isSearch) $whereParam = buildWhereClauseForSearch($searchField,$searchString,$searchOperator);  else $whereParam = NULL;    $paramArr['whereParam'] = $whereParam;  $paramArr['reload'] = TRUE;  /*  you can add aditional params in the where clause here:  $paramArr['outletid'] = $CI->session->userdata(SELECTED_OUTLET);  $paramArr['invtypeId'] = $CI->session->userdata(SELECTED_INVENTORY_TYPE);  $paramArr['postingYear'] = getPostingYear();  */  if( isset( $aData['method'] ) && isset( $aData['model'] ) ){  $CI->load->model( $aData['model'] );  $aDataList = $CI->$aData['model']->$aData['method']($paramArr);  $count = count($aDataList);  if( $count >0 ) $total_pages = ceil($count/$limit);  else $total_pages = 0;    if ($page > $total_pages) $page=$total_pages;  $start = $limit*$page - $limit;    $paramArr['start'] = $start;  $paramArr['limit'] = $limit;  $paramArr['sortField'] = $sidx;  $paramArr['sortOrder'] = $sord;  $paramArr['whereParam'] = $whereParam;  $paramArr['reload'] = TRUE;  $aDataList = $CI->$aData['model']->$aData['method']($paramArr);    $i=0;  if( isset( $aData['columns'] ) ){  foreach ($aDataList as $row)  {  $columnData = array();  foreach( $aData['columns'] as $sData ){  array_push( $columnData, $row->$sData );  }  $rs->rows[$i]['id'] = $row->$aData['pkid'];  $rs->rows[$i]['cell'] = $columnData ;  $i++;  }  }  $rs->cols = $columnData;  $rs->page = $page;  $rs->total = $total_pages;  $rs->records = $count;  echo json_encode($rs);  }    function buildWhereClauseForSearch($searchField,$searchString,$searchOperator) {  $searchString = mysql_real_escape_string($searchString);  $searchField = mysql_real_escape_string($searchField);  $operator['eq'] = "$searchField='$searchString'"; //equal to  $operator['ne'] = "$searchField<>'$searchString'"; //not equal to  $operator['lt'] = "$searchField < $searchString"; //less than  $operator['le'] = "$searchField <= $searchString "; //less than or equal to  $operator['gt'] = "$searchField > $searchString"; //less than  $operator['ge'] = "$searchField >= $searchString "; //less than or equal to  $operator['bw'] = "$searchField like '$searchString%'"; //begins with  $operator['bn'] = "$searchField not like '$searchString%'"; //not begins with  $operator['in'] = "$searchField in ($searchString)"; //in  $operator['ni'] = "$searchField not in ($searchString)"; //not in  $operator['ew'] = "$searchField like '%$searchString'"; //ends with  $operator['en'] = "$searchField not like '%$searchString%'"; //not ends with  $operator['cn'] = "$searchField like '%$searchString%'"; //in  $operator['nc'] = "$searchField not like '%$searchString%'"; //not in  $operator['nu'] = "$searchField is null"; //is null  $operator['nn'] = "$searchField is not null"; //is not null    if(isset($operator[$searchOperator])) {  return $operator[$searchOperator];  } else {  return null;  }  }  }