2011年6月30日 星期四

Play Framework 實驗筆記 4- 使用jqGrid 作資料維護

這一部分是將前端表格顯示的部份作改善。
使用的元件是jqGrid。這是jqGrid的Demo,裡面有許多使用範例,有興趣的可以去看一下,這邊只會用到以下這些簡單的功能。

1. 使用AJAX 的方式,向Server取得 JSON 格式的資料
2. 支援常見的分頁方式
3. 編輯時使用 inline editor 的方式

檔案位置:

檔案要放對位置
*.css 放在 N:\PlayFramework\play-1.1\members\public\stylesheets
css中用到的圖檔放在 N:\PlayFramework\play-1.1\members\public\stylesheets\images


*.js 放在 N:\PlayFramework\play-1.1\members\public\javascripts

View
View 的部份要將相關的js 檔include進來。我決定直接加在main.html
N:\PlayFramework\play-1.1\members\app\views\main.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title>#{get 'title' /}</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <link rel="stylesheet" type="text/css" media="screen" href="@{'/public/stylesheets/main.css'}">
  <link rel="stylesheet" type="text/css" media="screen" href="@{'/public/stylesheets/jquery-ui-1.8.12.custom.css'}">
  <link rel="stylesheet" type="text/css" media="screen" href="@{'/public/stylesheets/ui.jqgrid.css'}">
  
        #{get 'moreStyles' /}
        <link rel="shortcut icon" type="image/png" href="@{'/public/images/favicon.png'}">
        <script src="@{'/public/javascripts/jquery-1.4.2.min.js'}" type="text/javascript" charset="utf-8"></script>
        <script src="@{'/public/javascripts/jquery-ui-1.7.2.custom.min.js'}" type="text/javascript"></script>
  <script src="@{'/public/javascripts/grid.locale-cn.js'}" type="text/javascript"></script>
  <script src="@{'/public/javascripts/jquery.jqGrid.min.js'}" type="text/javascript"></script>

  #{get 'moreScripts' /}
    </head>
    <body>
           #{if flash.error}
            <p class="error">${flash.error}</p>
        #{/if}
        #{if flash.success}
            <p class="success">${flash.success}</p>
        #{/if}
        
        <div id="main">
            #{doLayout /} 
        </div>
    </body>
</html>

和controller對應的View要加入jqGrid元件

N:\PlayFramework\play-1.1\members\app\views\EnhanceMemberOperation\index.html
#{extends 'main.html' /}
#{set title:'Home' /}

Member Data
<table id="scroll37"></table>
<div id="pscroll37" ></div>

<script type="text/javascript">
 
jQuery.fn.log = function(msg) {
    if (typeof console != "undefined")
        console.log("%s: %o", msg, this);
    return this;
};
 
 var lastsel2

jQuery("#scroll37").jqGrid({
    url:'@{memberList()}',
 datatype: "json",
 height: 400,
 width: 800,
 editable: true,
    colNames:['ID','firstName', 'lastName','gender', 'email'],

 colModel:[
     {
        name:'memberid',
        index:'memberid',
        align : "right",
        width : 50, 
        required : true,
  hidden: true, 
  editable: false, 
  editrules: { edithidden: false }, hidedlg: true
      },{
        name:'firstName',
        index:'firstName',
        width:100,
        editable : true,
        required : true,
  editrules:{required:true}
      },{
        name:'lastName',
        index:'lastName',
        width:100,
        editable : true,
        required : true
      },{
        name:'gender',
        index:'gender',
        width:50, 
        editable : true,
        edittype : 'select',
        editoptions:{value:"1:男;2:女"},
  formatter:function(cellvalue, options, row){
       if(cellvalue==1 || cellvalue=="男" ){
    return "男";
      }else{
          return "女";
     }
  },

        required : true
      },{
        name:'email',
        index:'email',
        width:150, 
        editable : true,
        required : true
      }
    ],
    rowNum:20,
 rowTotal: 100,
 rowList : [20,30,50],
 //scroll:2,
 headertitles: false,
 loadonce:false,
    mtype: "GET",
 editurl: '@{memberEdit()}', 
 rownumbers: true,
 rownumWidth: 40,
 gridview: true,
    pager: '#pscroll37',
    sortname: 'id',
    viewrecords: true,
    sortorder: "asc",
 caption: "Member Data",


 onSelectRow: function(id){
 
      if(id && id!==lastsel2){
 
        jQuery('#scroll37').saveRow(lastsel2);
  $("#scroll37").jqGrid('setGridParam', {editurl:'@{memberEdit()}?memberId='+$('#scroll37').jqGrid('getCell',id, 1)})
  jQuery('#scroll37').editRow(id,true);
        lastsel2=id;
      }
   
    }

});

jQuery("#scroll37").jqGrid('navGrid','#pscroll37',{del:true,add:true,edit:true});

</script>


Controller
由於新增了ajax的功能,所以controller 的部份要使用 renderJSON() 作輸出
N:\PlayFramework\play-1.1\members\app\controllers\EnhanceMemberOperation.java

package controllers;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import models.Member;
import models.MemberCard;
import play.data.validation.Required;
import play.mvc.Controller;

public class EnhanceMemberOperation extends Controller {
    public static void index() { 
        render();
   }

    public static void memberEdit(@Required String oper, long memberId,String firstName,String lastName ,Integer gender, String email) {
     if(validation.hasErrors()) {
            params.flash(); // add http parameters to the flash scope
            validation.keep(); // keep the errors for the next request
            System.out.println("ERROR: "+ validation.errors());
            index();
        }
        if (oper.equalsIgnoreCase("add")){
         new Member(firstName,lastName,gender,email).insert();
        }else if (oper.equalsIgnoreCase("del")){
         Member member = Member.findById(memberId);
         member.delete();
        }else if (oper.equalsIgnoreCase("edit")){
         Member member = Member.findById(memberId);
         member.firstName = firstName;
         member.lastName = lastName;
         member.gender = gender;
         member.email = email;
         member.update();
        }
        index();
    }
    
    public static void memberList(int page, int rows ,int sidx ,int  sord ) {

      System.out.println("進入memberList表單" +  params.get("page")+":" + params.get("rows"));
      int totalRecords= Member.all().count();
     int totalPage = (int) java.lang.Math.ceil(new Double(totalRecords) / new Double(rows));
     System.out.println("totalPage=" +  totalPage +" totalRecords=" + totalRecords);
     Hashtable ht = new Hashtable();
  ArrayList al = new ArrayList();
  
  int start = (page - 1) * rows;
  List<Member> members = Member.all().fetch(rows,start);
  for (int i=0;i<members.size();i++){
   Hashtable rowdata = new Hashtable();
   ArrayList columns = new ArrayList();
   columns.add(members.get(i).id);
   columns.add(members.get(i).firstName);
   columns.add(members.get(i).lastName);
   columns.add(members.get(i).gender);
   columns.add(members.get(i).email);
   rowdata.put("id",i);
   rowdata.put("cell",columns);
   al.add(rowdata);
  }

  ht.put("page",page);
  ht.put("total",totalPage);
  ht.put("records",totalRecords);
  ht.put("rows",al);
        renderJSON(ht);
      
    }

    
    public static void memberDelete(Long id) {
     Member member = Member.findById(id);
        notFoundIfNull(member); 
        member.delete();
        flash.success("The member %s has been deleted", member.firstName  );
        index();
    }
}



執行結果如下圖: