2014-01-07 6 views
0

Взгляните на мою сетку; grid В последнем рассмотренном столбце возвращается крошечное значение int (0 или 1) из базы данных MySQL. То, что я пытаюсь добиться, чтобы отображать только строки, в которых рассмотрены = 0 и все еще быть в состоянии использовать поиск для выполнения запроса и получения полей, где рассмотрел = 1. Я хочу отобразить строки, где рассмотрено = 0, когда сетка изначально загружается. Я попытался сделать эту серверную часть, используя код "SELECT * FROM table WHERE reviewed = 0". В этом случае запрос работает, но поиск не работает. Есть ли способ сделать это на клиенте? Пожалуйста, помогите мне в решении этой проблемы в течение нескольких дней. Я попробовал почти все.Запрос на стороне сервера JqGrid конфликтует с поиском

Here's my server side code; 
//Get the requested page 
$page = $_GET['page']; 

//Get how many rows we want to have into the grid 
$limit = $_GET['rows']; 

// get index row - i.e. user click to sort. At first time sortname parameter - 
// after that the index from colModel 
$sidx = $_GET['sidx']; 

// sorting order - at first time sortorder 
$sord = $_GET['sord']; 

// if we not pass at first time index use the first column for the index or what you want 
if(!$sidx) $sidx =1; 

//array to translate the search type 
$ops = array(
    'eq'=>'=', //equal 
    'ne'=>'<>',//not equal 
    'lt'=>'<', //less than 
    'le'=>'<=',//less than or equal 
    'gt'=>'>', //greater than 
    'ge'=>'>=',//greater than or equal 
    'bw'=>'LIKE', //begins with 
    'bn'=>'NOT LIKE', //doesn't begin with 
    'in'=>'LIKE', //is in 
    'ni'=>'NOT LIKE', //is not in 
    'ew'=>'LIKE', //ends with 
    'en'=>'NOT LIKE', //doesn't end with 
    'cn'=>'LIKE', // contains 
    'nc'=>'NOT LIKE' //doesn't contain 
); 
function getWhereClause($col, $oper, $val){ 
    global $ops; 
    if($oper == 'bw' || $oper == 'bn') $val .= '%'; 
    if($oper == 'ew' || $oper == 'en') $val = '%'.$val; 
    if($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') $val = '%'.$val.'%'; 
    return " WHERE $col {$ops[$oper]} '$val' "; 
} 
$where = ""; //if there is no search request sent by jqgrid, $where should be empty 
$searchField = isset($_GET['searchField']) ? $_GET['searchField'] : false; 
$searchOper = isset($_GET['searchOper']) ? $_GET['searchOper']: false; 
$searchString = isset($_GET['searchString']) ? $_GET['searchString'] : false; 
if ($_GET['_search'] == 'true') { 
    $where = getWhereClause($searchField,$searchOper,$searchString); 
    } 

mysql_query("SET NAMES 'utf8'"); 

// calculate the number of rows for the query. We need this for paging the result 
$result = mysql_query("SELECT COUNT(*) AS count FROM renal_apptRequest"); 
$row = mysql_fetch_array($result,MYSQL_ASSOC); 
$count = $row['count']; 

// calculate the total pages for the query 
if($count > 0 && $limit > 0) { 
       $total_pages = ceil($count/$limit); 
} else { 
       $total_pages = 0; 
} 

// if for some reasons the requested page is greater than the total 
// set the requested page to total page 
if ($page > $total_pages) $page=$total_pages; 

// calculate the starting position of the rows 
$start = $limit*$page - $limit; 

// if for some reasons start position is negative set it to 0 
// typical case is that the user type 0 for the requested page 
if($start <0) $start = 0; 

// the actual query for the grid data 
    $SQL = "SELECT * FROM renal_apptRequest".$where." ORDER BY $sidx $sord LIMIT $start , $limit"; 
$result = mysql_query($SQL) or die("Couldn't execute query.".mysql_error()); 

Вот мой код клиента

$(function() { 
       $("#list").jqGrid({ 
      url:"grid_apptRequest.php", 
      datatype: "json", 
      mtype: "GET", 
      colNames:["ID","Date","referralType","patientName","patientAddress","patientDOB","referralProvider","referralReason","contactName","contactPhone","contactEmail","contactFax","preferredTime","comments","reviewed"], 
      colModel: [ 
     { name: "id",index:'id', width: 55,search:true, formatter:'showlink',formatoptions:{baseLinkUrl:'renal_apptRequest_review.php', target:'_blank'}}, 
     { name: "date",index:'date',search:true, width: 90 }, 
     { name: "referralType",index:'referralType',search:true, width: 80}, 
     { name: "patientName",index:'patientName',search:true, width: 120}, 
     { name: "patientAddress",index:'patientAddress',search:true, width: 120}, 
     { name: "patientDOB",index:'patientDOB',search:true, width: 90 }, 
     { name: "referralProvider",index:'referralProvider',search:true, width: 90 }, 
     { name: "referralReason",index:'referralReason',search:true, width: 120 }, 
     { name: "contactName",index:'contactName',search:true, width: 100}, 
     { name: "contactPhone",index:'contactPhone',search:true, width: 100}, 
     { name: "contactEmail",index:'contactEmail',search:true, width: 100 }, 
     { name: "contactFax",index:'contactFax',search:true, width: 80}, 
     { name: "preferredTime",index:'preferredTime',search:true, width: 70 }, 
     { name: "comments",index:'comments',search:true, width: 100 }, 
     { name: "reviewed",index:'reviewed',search:true,hidedlg:true, width: 60, align: "right" } 
    ], 
     pager: "#pager", 
     rowNum: 10, 
     rowList: [10,20,30], 
     autowidth:true, 
     sortname: "id", 
     sortorder: "asc", 
     viewrecords: true, 
     gridview: true, 
     autoencode: true, 
     caption: "Appointment Request", 

     afterInsertRow: function (id, currentData, jsondata) { 
    if(currentData.reviewed == 1){ 
      $('#list').jqGrid('delRowData',id); 
    } 

} 
      }).navGrid("#pager", {search:true, edit:false,add:false,del:false,searchtext:"Search"}); 

сторона Вот пример данных JSON, которая заполняет мою сетку. Это делается на стороне сервера. $ cipher-> decryptThis() - это алгоритм дешифрования, используемый для дешифрования зашифрованных полей из базы данных.

$responce = new stdClass(); 
$responce->page = $page; 
$responce->total = $total_pages; 
$responce->records = $count; 
$i=0; 
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
{ 
    $responce->rows[$i]['id']=$row['id']; 
    $responce->rows[$i]['cell']=array($row['id'],$row['date'],$row['referralType'],$cipher->decryptThis($row['patientName']),$cipher->decryptThis($row['patientAddress']),$cipher->decryptThis($row['patientDOB']),$row['referralProvider'], $cipher->decryptThis($row['referralReason']),$cipher->decryptThis($row['contactName']) 
    ,$cipher->decryptThis($row['contactPhone']),$cipher->decryptThis($row['contactEmail']), $row['contactFax'],$row['preferredTime'],$row['comments'], 
    $row['reviewed'] ); 
    $i++; 
} 
echo json_encode($responce); 
+0

Итак, вы не хотите отображать строки при просмотре> 0? Это верно? – avijendr

+0

Проверено может быть только 1 0r 0 и да Я не хочу отображать строку при просмотре = 1. –

+0

Немного смущает этот оператор> SELECT * FROM table WHERE review = 0 (запрос работает, но поиск не удается). Вы хотите сказать, что поиск не удается, когда вы выбираете столбец обзора в качестве критерия поиска? – avijendr

ответ

0

Я не эксперт по php. Мой опыт - jqgrid. В jqgrid вы можете сделать это с помощью взлома, используя событие afterinsertRow. В коде добавьте следующее. Это удалит строки, которые Досталось рассмотрел = 1

caption: "Appointment Request", 
    afterInsertRow: function (id, currentData, jsondata) { 

     if(currentData.reviewed == '1'){ 
     // I am not sure if reviewed is string or number. If the above 
     // doesn't work try currentData.reviewed == 1 
     $('#list').jqGrid('delRowData',id); 
     } 

    }, 

Ваш код PHP выглядит немного неудобный. Некоторые настройки там могут помочь вам достичь этого там, но, как я сказал, я не эксперт по php, поэтому я не могу этого гарантировать. Но вышеупомянутый код определенно делает трюк.

What does afterInsertRow does:

  • пожары Это событие после каждой вставленной строки.
  • rowid - это идентификатор вставленного ряда
  • rowdata - это массив данных, которые необходимо вставить в строку. Это массив типа name: value, где имя - это имя из colModel
  • rowelem - это элемент ответа. Если данные являются xml, это xml-элемент строки; если данные JSON это массив, содержащий все данные для строки
  • Примечание: это событие не срабатывает, если GridView параметр установлен в значение истинного
+0

Я пробовал код выше, но он не работает. –

+0

Я тестировал свою локальную машину, и она отлично работает (хотя данные разные). Не могли бы вы обновить свой вопрос с помощью последнего клиентского кода. Также было бы здорово, если бы вы могли опубликовать часть своего json. – avijendr

+0

Я только что обновил вопрос с помощью нового клиентского кода и JSON. Спасибо –

0

Самый лучший способ сделать это, чтобы сгруппировать данные по поле интересов в моем случае рассмотрел. Этот фрагмент кода делает трюк. Вставьте его перед заголовком вашей сетки.

grouping:true, 
      groupingView : { 
      groupField : ['reviewed'], 
      groupColumnShow : [true], 
      groupText:['<b>{0} - {1} Item(s)</b>'], 
      groupCollapse : true, 
      groupOrder: ['desc'] 
      }, 
Смежные вопросы