Translate

[jqGrid] 데이터 조작 설명







실습 jqGrid 버전: CDN 제공하는 v4.6 버전으로 테스트



Data Manipulation

처음의 jqGrid는 유일하게 XML 데이터로만 기능이 지원됐으나 사람들의 요청으로 JSON, Array 데이터, 그리고 실제 이름을 사용하여 데이터 지원기능이 추가되었다.
1004lucifer

 datatype 옵션에 사용 가능한 값

 1. xml
 2. json
 3. jsonp
 4. array
 5. xmlstring
 6. jsonstring
 7. script
 8. function (...)






기본 매핑 값

 - XML data
jQuery("#gridid").jqGrid({
...
   xmlReader : { 
      root: "rows", 
      row: "row", 
      page: "rows>page", 
      total: "rows>total", 
      records : "rows>records", 
      repeatitems: true, 
      cell: "cell", 
      id: "[id]",
      userdata: "userdata",
      subgrid: { 
         root:"rows", 
         row: "row", 
         repeatitems: true, 
         cell:"cell" 
      } 
   },
...
});


 - JSON data
jQuery("#gridid").jqGrid({
...
   jsonReader : { 
      root: "rows", 
      page: "page", 
      total: "total", 
      records: "records", 
      repeatitems: true, 
      cell: "cell", 
      id: "id",
      userdata: "userdata",
      subgrid: { 
         root:"rows", 
         repeatitems: true, 
         cell:"cell" 
      } 
   },
...
});


PS.
colModel에서 XML필드의 설명을 위한 xmlmap 옵션, JSON필드의 설명을 위한 jsonmap 옵션을 지정할 수 있다.
jQuery("#gridid").jqGrid({
...
   colModel : [ {name:'amount',..., xmlmap:'amt'...}...],
...
});
(repeatitems 옵션이 false로 설정되어있는경우)
위와같이 작업 시 jqGrid에서 XML data에서 amt 태그를 찾는다.





XML Data

 - datatype 옵션과 xmlReader 옵션을 지정하지 않으면 jqGrid는 기본적으로 XML 형식의 데이터를 위에 설명한 기본 매핑값에 기초한 자료의 구조를 따라간다.
하지만 서버의 Response를 조작할 수 없는 상황이 있을 수 있으며 이럴때 xmlReader를 사용할 수 있으며, colModel에 몇가지 추가사항이 있다.
아래의 xmlReader의 예제를 참조해라.
1004lucifer
jQuery("#gridid").jqGrid({
...
   xmlReader : { 
      root: "rows", 
      row: "row", 
      page: "rows>page", 
      total: "rows>total", 
      records : "rows>records", 
      repeatitems: true, 
      cell: "cell", 
      id: "[id]",
      userdata: "userdata",
      subgrid: { 
         root:"rows", 
         row: "row", 
         repeatitems: true, 
         cell:"cell" 
      } 
   },
...
});

중요: XML에서 요소에 접근하는 규칙은 jQuery 라이브러리에서 사용되는 규칙, 즉 CSS 패턴과 동일하다.

 * jqGrid v4.3 기준으로 XML응답의 모든 속성을 읽을 수 있으며, 태그를 함수로 설정할 수 있다.



 - root element
첫번째로 root 요소를 정의해야 한다. 데이터의 시작과 다른 루프의 시작점을 지정한다.

데이터
<invoices> 
   <request>true</request> 
   ... 
   <result> 
      <row> 
         <cell>data1</cell> 
         <cell>data2</cell> 
         <cell>data3</cell> 
         <cell>data4</cell> 
         <cell>data5</cell> 
         <cell>data6</cell> 
      </row> 
      ... 
   </result> 
</invoices>
root 요소를 result로 지정한경우 모든데이터가 처리되며, 행들은 <row>로 되어있고 셀들은 <cell>로 되어있다.
이런경우 아래와 같이 root를 지정한다.
jQuery("#gridid").jqGrid({
...
   xmlReader: { root:"result" },
...
});



 - row element
행에대한 정보를 기술하며, root 요소의 하위요소 이어야 한다.

데이터
<invoices> 
   <request>true</request> 
   ... 
   <result> 
      <invoice> 
         <cell>data1</cell> 
         <cell>data2</cell> 
         <cell>data3</cell> 
         <cell>data4</cell> 
         <cell>data5</cell> 
         <cell>data6</cell> 
      </invoice> 
      ... 
   </result> 
</invoices>
위와 같을 때 아래와 같이 설정한다.
jQuery("#gridid").jqGrid({
...
   xmlReader: { root:"result", row:"invoice"  },
...
});



 - page, total, records
Pager에 필요한 정보를 기술하며, 루트요소의 자식요소 이어야 하며 반드시 필요하지는 않다.

데이터
<invoices> 
   <request>true</request> 
   ... 
   <currentpage>1</currentpage>
   <totalpages>10</totalpages>
   <totalrecords>20</totalrecords>
   <result> 
      <invoice> 
         <cell>data1</cell> 
         <cell>data2</cell> 
         <cell>data3</cell> 
         <cell>data4</cell> 
         <cell>data5</cell> 
         <cell>data6</cell> 
      </invoice> 
      ... 
   </result> 
</invoices>
위와 같을 때 아래와 같이 설정한다.
jQuery("#gridid").jqGrid({
...
   xmlReader: { 
      root:"result", 
      row:"invoice",
      page:"invoices>currentpage", 
      total:"invoices>totalpages", 
      records:"invoices>totalrecords"
  },
...
});



 - repeatitems, cell element
repeatitems와 cell항목은 jqGrid에게 반복가능한 행의 데이터에 대해서 지정한다.
아래와 같이 cell 항목이 모두 같은 태그로 되어있는 경우가 그렇다.

데이터
<invoices> 
   <request>true</request> 
   ... 
   <currentpage>1</currentpage>
   <totalpages>10</totalpages>
   <totalrecords>20</totalrecords>
   <result> 
      <invoice> 
         <invcell>data1</invcell> 
         <invcell>data2</invcell> 
         <invcell>data3</invcell> 
         <invcell>data4</invcell> 
         <invcell>data5</invcell> 
         <invcell>data6</invcell> 
      </invoice> 
      ... 
   </result> 
</invoices>
위와 같을 때 아래와 같이 설정한다.
jQuery("#gridid").jqGrid({
...
   xmlReader: { 
      root:"result", 
      row:"invoice",
      page:"invoices>currentpage", 
      total:"invoices>totalpages", 
      records:"invoices>totalrecords",
      repeatitems:true,
      cell:"invcell"
  },
...
});



 - id
repeatitems가 true로 설정되었고 colModel에서 id에 대한 key옵션이 설정되지 않은경우 XML데이터에서 행의 속성으로 지정할 수 있다.

데이터
<invoices> 
   <request>true</request> 
   ... 
   <currentpage>1</currentpage>
   <totalpages>10</totalpages>
   <totalrecords>20</totalrecords>
   <result> 
      <invoice asin='12345'> 
         <invcell>data1</invcell> 
         <invcell>data2</invcell> 
         <invcell>data3</invcell> 
         <invcell>data4</invcell> 
         <invcell>data5</invcell> 
         <invcell>data6</invcell> 
      </invoice> 
      ... 
   </result> 
</invoices>
이 경우 xmlReader는 아래와 같다.
jQuery("#gridid").jqGrid({
...
   xmlReader: { 
      root:"result", 
      row:"invoice",
      page:"invoices>currentpage", 
      total:"invoices>totalpages", 
      records:"invoices>totalrecords",
      repeatitems:true,
      cell:"invcell",
      id : "[asin]"
  },
...
});



 - 예제

데이터
<invoices> 
   <request>true</request> 
   ... 
   <currentpage>1</currentpage>
   <totalpages>10</totalpages>
   <totalrecords>20</totalrecords>
   <result> 
      <invoice> 
         <asin>12345</asin>
         <invoiceno>data1</invoiceno>
         <invoicedate>data2</invoicedate> 
         <invoiceamount>data3</invoiceamount> 
         <invoicetax>data4</invoicetax> 
         <invoicetotal>data5</invoicetotal> 
         <notes>data6</notes> 
      </invoice> 
      ... 
   </result> 
</invoices>
여기서 <asin> 태그는 고유한 ID이며 그리드에서 row id로 설정되어야 하며 표시되지 않아야 한다고 할 때 아래와 같이 할 수 있다.
jQuery("#gridid").jqGrid({
...
   colModel :[ 
      {name:'invid', index:'invid', width:55, xmlmap:"invoiceno"}, 
      {name:'invdate', index:'invdate', width:90, xmlmap:"invoicedate"}, 
      {name:'amount', index:'amount', width:80, align:'right', xmlmap:"invoiceamount"}, 
      {name:'tax', index:'tax', width:80, align:'right', xmlmap:"invoicetax"}, 
      {name:'total', index:'total', width:80, align:'right', xmlmap:"invoicetotal"}, 
      {name:'note', index:'note', width:150, sortable:false, xmlmap:"notes"} 
   ],
   xmlReader: { 
      root:"result", 
      row:"invoice",
      page:"invoices>currentpage", 
      total:"invoices>totalpages", 
      records:"invoices>totalrecords",
      repeatitems:false,
      id : "asin"
  },
...
});
만약 colModel의 이름이 중요한게 아니라면 아래와 같이 사용도 가능하다.
jQuery("#gridid").jqGrid({
...
   colModel :[ 
      {name:'invoiceno', index:'invid', width:55}, 
      {name:'invoicedate', index:'invdate', width:90}, 
      {name:'invoiceamount', index:'amount', width:80, align:'right'}, 
      {name:'invoicetax', index:'tax', width:80, align:'right'}, 
      {name:'invoicetotal', index:'total', width:80, align:'right'}, 
      {name:'notes', index:'note', width:150, sortable:false} 
   ],
   xmlReader: { 
      root:"result", 
      row:"invoice",
      page:"invoices>currentpage", 
      total:"invoices>totalpages", 
      records:"invoices>totalrecords",
      repeatitems:false,
      id : "asin"
  },
...
});

즉 jqGrid는 xmlmap옵션이 있는지 확인하며 이 옵션이 없는경우 name이 xmlmap으로 사용된다.
하지만 xmlReader의 repeatitems가 false로 설정되어있는 경우에만 사용 가능하다.







XML String

 - xmlstring 옵션은 XML옵션과 유사하며 위의 설명을 참조해라.
유일한 차이점은 데이터가 문자열로 전달되며 이 XML데이터는 유효해야한다.
그리고 datastr 옵션을 사용할수가 있다.
1004lucifer
<script>
var mystr =
"<?xml version='1.0' encoding='utf-8'?>
<invoices>
    <rows>
        <row>
            <cell>data1</cell>
            <cell>data2</cell>
            <cell>data3</cell>
            <cell>data4</cell>
            <cell>data5</cell>
            <cell>data6</cell>    
        </row>
    </rows>
</invoices>";
 
jQuery(document).ready(function(){ 
  jQuery("#list").jqGrid({
    datatype: 'xmlstring',
    datastr : mystr,
    colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],
    colModel :[ 
      {name:'invid', index:'invid', width:55, sorttype:'int'}, 
      {name:'invdate', index:'invdate', width:90, sorttype:'date', datefmt:'Y-m-d'}, 
      {name:'amount', index:'amount', width:80, align:'right', sorttype:'float'}, 
      {name:'tax', index:'tax', width:80, align:'right', sorttype:'float'}, 
      {name:'total', index:'total', width:80, align:'right', sorttype:'float'}, 
      {name:'note', index:'note', width:150, sortable:false} ],
    pager: '#pager',
    rowNum:10,
    viewrecords: true,
    caption: 'My first grid'
  }); 
}); 
</script>
위의 예에서 colModel에 sorttype 옵션이 있는데 이 옵션은 xmlstring을 사용할 때 jqGrid에서 클라이언트 사이드의 특정 컬럼의 소팅 기능을 제공한다.


PS.
XML string을 데이터로 사용할 수 있으며, 데이터를 조회한 후 datatype옵션이 자동으로 local로 설정된다.
(현재 페이징 기능이 동작하지 않음)



XML 주의사항
xmlReader의 repeatitems 옵션이 true인 경우
 - row요소의 cell의 갯수는 colModel에서 정의한 컬럼의 갯수와 같아야 한다.
 - colModel의 key옵션을 사용하여 row의 id를 설정할 수 있다.

xmlReader의 repeatitems 옵션이 false인 경우
 - row요소의 cell의 갯수가 colModel에서 정의한 컬럼과 같아야 할 필요는 없다.
 - row 태그는 다른 자식 element를 포함할 수 없다 (음!? 이부분은 뭔가 이상하다)





JSON Data

 - JSON Data는 XML Data와 매우 유사한 방식으로 처리가 되며, 중요한것은 jsonReader가 전달받은 데이터와 일치한다는 것이다.

 * jqGrid v3.6.5기준으로 JSON string은 유효한 JSON값 이어야 하며 https://json.org를 참고해라

datatype: json or jsonp or jsonstring


jQuery("#gridid").jqGrid({
...
   jsonReader : {
     root: "rows",
     page: "page",
     total: "total",
     records: "records",
     repeatitems: true,
     cell: "cell",
     id: "id",
     userdata: "userdata",
     subgrid: {root:"rows", 
        repeatitems: true, 
       cell:"cell"
     }
   },
...
});
위와같이 기본 jsonReader는 아래와 같은 데이터를 기대한다.
{ 
  "total": "xxx", 
  "page": "yyy", 
  "records": "zzz",
  "rows" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell":["cell21", "cell22", "cell23"]},
      ...
  ]
}


여기서 사용하는 속성의 설명은 아래의 표와 같다.
TagDescription
total조회 할 전체 페이지
page조회 할 현재 페이지
record조회 할 레코드의 전체 갯수
rows실제 데이터를 포함하고 있는 배열
id행의 고유 id
cell행의 데이터를 가지고 있는 배열

jsonReadeer의 구조는 xmlReader와 매우 유사하며, 유일하게 누락된 부분은 JSON데이터가 필요하지 않은 row요소이다.


 - root element
데이터의 시작되는 곳을 의미하며, 데이터가 들어있는 배열을 가리킨다.

jQuery("#gridid").jqGrid({
...
   jsonReader : {root:"invdata"},
...
});
위와 같이 셋팅하면 데이터는 다음과 같다.
{ 
  "total": "xxx", 
  "page": "yyy", 
  "records": "zzz",
  "invdata" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell":["cell21", "cell22", "cell23"]},
      ...
  ]
}



 - page, total, records element
Pager에서 필요한 데이터

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords"
   },
...
});
위와 같이 셋팅하면 데이터는 다음과 같다.
{ 
  "totalpages": "xxx", 
  "currpage": "yyy",
  "totalrecords": "zzz",
  "invdata" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell" :["cell21", "cell22", "cell23"]},
      ...
  ]
}



 - cell element
row의 데이터가 들어있는 배열

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "invrow"
   },
...
});
위와 같이 셋팅하면 데이터는 다음과 같다.
{ 
  "totalpages": "xxx", 
  "currpage": "yyy",
  "totalrecords": "zzz",
  "invdata" : [
    {"id" :"1", "invrow" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "invrow" :["cell21", "cell22", "cell23"]},
      ...
  ]
}



 - id element
행의 고유한 id

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "invrow",
      id: "invid"
   },
...
});
위와 같이 셋팅하면 데이터는 다음과 같다.
{ 
  "totalpages": "xxx", 
  "currpage": "yyy",
  "totalrecords": "zzz",
  "invdata" : [
    {"invid" :"1", "invrow" :["cell11", "cell12", "cell13"]},
    {"invid" :"2", "invrow" :["cell21", "cell22", "cell23"]},
      ...
  ]
}

아래와 같이 cell 요소를 빈문자열로 설정할수 있으며 id를 숫자로 설정하는것도 가능하다.
( 0인경우 첫번째 요소, 1이면 두번째 요소로 매칭됨 )
jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "",
      id: "0"
   },
...
});
{ 
  "totalpages" : "xxx", 
  "currpage" : "yyy",
  "totalrecords" : "zzz",
  "invdata" : [
    ["1", "cell11", "cell12", "cell13"],
    ["2", "cell21", "cell22", "cell23"],
      ...
  ]
}



 - repeatitems element
jqGrid에게 행의 데이터가 반복가능함을 알려주며 위에서 cell요소의 설명과 같이 동일한 태그 cell을 가지고 있다.
false로 설정 시 jqGrid가 json data의 요소를 name으로 검색하도록 한다.
colModel의 name옵션 또는 jsonmap옵션으로 name을 지정한다.

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      repeatitems: false,
      id: "0"
   },
...
});
위와 같이 셋팅하면 데이터는 다음과 같으며 이경우 'invid'가 id요소가 된다.
{ 
  "totalpages" : "xxx", 
  "currpage" : "yyy",
  "totalrecords" : "zzz",
  "invdata" : [
    {"invid" : "1","invdate":"cell11", "amount" :"cell12", "tax" :"cell13", "total" :"1234", "note" :"somenote"},
    {"invid" : "2","invdate":"cell21", "amount" :"cell22", "tax" :"cell23", "total" :"2345", "note" :"some note"},
      ...
  ]
}
1004lucifer
유용한 기능중에 (repeatitems가 false인경우) colModel에 지정한 모든 데이터를 포함할 필요가 없으며, name으로 검색하기 때문에 colModel의 순서와 데이터의 순서가 동일할 필요도 없다.
따라서 아래 데이터는 문제가 없다.
{ 
  "totalpages" : "xxx", 
  "currpage" : "yyy",
  "totalrecords" : "zzz",
  "invdata" : [
    {"invid" :"1", "invdate" : "cell11", "note" :"somenote"},
    {"invid" :"2", "amount" : "cell22", "tax" :"cell23", "total" :"2345"},
      ...
  ]
}







JSON String
jsonstring 옵션은 json과 기능이 동일하다. 유일한 차이점은 데이터가 문자열이며, 이경우 올바른 JSON데이터 형식이어야 한다.
이경우 datastr옵션을 사용하며 위의 XML String 에서의 설명을 참고해라.


PS.
jsonstring을 사용하는경우 데이터를 조회한 후 datatype옵션이 자동으로 local로 설정된다.
(현재 페이징 기능이 동작하지 않음)





JSON dot Notation (JSON 점 표기법)

 - (repeatitems 옵션이 false인경우) JSON데이터가 이름값을 사용하는경우 점표기법과 색인표기법을 사용할 수 있다.

jQuery("#gridid").jqGrid({
...
 colModel:[
   {name:'name',label:'Name', width:150,editable: true},
   {name:'id',width:50, sorttype:"int", editable: true,formatter:strongFmatter},
   {name:'email',label:'Email', width:150,editable: true,formatter:'email'},
   {name:'stock',label:'Stock', width:60, align:"center", editable: true,formatter:'checkbox',edittype:"checkbox"},
   {name:'item.price',label:'Price', width:100, align:"right", editable: true,formatter:'currency'},
   {name:'item.weight',label:'Weight',width:60, align:"right", editable: true,formatter:'number'},
   {name:'ship',label:'Ship Via',width:90, editable: true,formatter:'select', edittype:"select",editoptions: value:"2:FedEx;1:InTime;3:TNT;4:ARK;5:ARAMEX"}},      
   {name:'note',label:'Notes', width:100, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"20"}}      
 ],
...
});
위와 같이 colModel에서 위와같이 item.price 요소와 item.weight 요소를 정의하면 데이터는 아래와 같다.
{
   "page":"1",
   "total":2,
   "records":"13", 
   "rows":[ 
      {"id":"12345","name":"Desktop Computers","email":"josh@josh.com","item":{"price":"1000.72", "weight": "1.22" }, "note": "note", "stock": "0","ship": "1"}, 
      {"id":"23456","name":"<var>laptop</var>","note":"Long text ","stock":"yes","item":{"price":"56.72", "weight":"1.22"},"ship": "2"},
      {"id":"34567","name":"LCD Monitor","note":"note3","stock":"true","item":{"price":"99999.72", "weight":"1.22"},"ship":"3"},
      {"id":"45678","name":"Speakers","note":"note","stock":"false","ship":"4"} 
    ] 
}







jsonReader as Function

 - 특정 상황에서는 Web Service 에서 데이터를 얻을 수 도 있는데, 이 경우 그리드가 동작하는데 필요한 모든 요소를 response에 구성하지 못할 수 도 있다.
jqGrid v3.6.4 기준으로 jsonReader의 요소를 함수로 정의가 가능하다.

jsonReader: {
    repeatitems: false,
    id: "Id",
    root: function (obj) { return obj; },
    page: function (obj) { return 1; },
    total: function (obj) { return 1; },
    records: function (obj) { return obj.length; }
}
여기서 obj는 service/server의 응답이다.





Array Data

 - jqGrid의 주요 목적은 서버를 통해 DB에서 받아온 동적인 데이터를 보여주는 것이지만 배열 데이터를 이용해 클라이언트 측에서 데이터 조작이 가능하도록 지원도 한다.

Array 관련 옵션: datatype
colModel 관련 옵션: sorttype, datefmt
관련 메소드: getRowData, delRowData, setRowData, addRowData, updateGridRows (링크 참고)

* jqGrid v3.7부터 data, localReader 두개의 옵션이 도입되었으며, data옵션은 그리드 옵션에 설명되어 있고 localReader옵션은 jsonReader와 동일한 기능을 가지지만 로컬 배열 데이터에 적용된다.


localReader는 jsonReader와 동일한 초기값을 갖는다.
localReader = {
   root: "rows",
   page: "page",
   total: "total",
   records: "records",
   repeatitems: false,
   cell: "cell",
   id: "id",
   userdata: "userdata",
   subgrid: {root:"rows", repeatitems: true, cell:"cell"}
}
jsonReader의 모든 유효한 작업을 localReader에 적용 가능하다.



먼저 아래와 같이 데이터가 local에 있다는 것을 jqGrid에 알려준다.
jQuery("#grid_id").jqGrid({
...
   datatype: "clientSide",
...
});
위 방법은 datatype: 'local'과 동일하다.



 - 소팅
컬럼의 sorttype을 설정할 수 있으며 지정하지 않으면 기본적으로 'text'로 지정된다.
<script>
jQuery(document).ready(function(){ 
    jQuery("#list").jqGrid({
        datatype: 'clientSide',
        colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],
        colModel :[ 
        {name:'invid',index:'invid', width:55, sorttype:'int'}, 
        {name:'invdate',index:'invdate', width:90, sorttype:'date', datefmt:'Y-m-d'}, 
        {name:'amount',index:'amount', width:80, align:'right',sorttype:'float'}, 
        {name:'tax',index:'tax', width:80, align:'right',sorttype:'float'}, 
        {name:'total',index:'total', width:80,align:'right',sorttype:'float'}, 
        {name:'note',index:'note', width:150, sortable:false} ],
        pager: '#pager',
        rowNum:10,
        viewrecords: true,
        caption: 'My first grid'
   }); 
...
}); 
</script>
가능한 소팅 타입은 int, float, date, text가 있으며, 정렬 유형의 날짜에 대해서는 포멧을 알아야 한다. (기본값은 ISO형식: 'Y-m-d')



 - 데이터 추가

jQuery("#grid_id").addRowData( rowid, data, position, srcrowid );
rowid: row의 id
data: name:value 형식의 데이터의 배열, name은 colModel의 name과 같다.
position: 데이터를 추가할 때 first, last, after 사용.
 - first: 그리드의 최상단에 새로운 행을 추가
 - last: 마지막 위치에 행을 추가
 - before, after: scrowid의 행과 관련이 있다.(subGrid 이야기 하는것 같음)
scrowid: before, after로 추가되는 신규 데이터의 id


<script>
...
var myfirstrow = {invid:"1", invdate:"2007-10-01", note:"note", amount:"200.00", tax:"10.00", total:"210.00"};
jQuery("#list").addRowData("1", myfirstrow);
...
</script>
위와같이 하나의 row를 추가했고 name:value의 순서는 상관이 없으며, 아래와 같이 name:value 쌍을 하나만 설정도 가능하다.
(두번째 행으로 amount 컬럼의 데이터만 추가)
<script>
...
jQuery("#list").addRowData("2", {amount:"300.00"});
...
</script>



 - 데이터 가져오기

jQuery("#grid_id").getRowData( rowid );
rowid: 특정 row의 id값


jQuery("#list").getRowData( "1" );
위와 같이 지정 시 아래와 같이 데이터가 리턴된다.
{invid:"1", invdate:"2007-10-01", note:"note", amount:"200.00", tax:"10.00", total:"210.00"};



 - 데이터 삭제

jQuery("#grid_id").delRowData( rowid );
rowid: 삭제할 row의 id
1004lucifer

jQuery("#list").delRowData( "2" );
위와 같이 작업 시 id가 2인 row를 삭제하며 성공 시 true를 반환, 그외 false를 반환한다.



 - 데이터 변경

jQuery("#grid_id").setRowData( rowid, data );
rowid: 값을 변경할 row의 id
data: 새로운 값의 배열데이터 (name:value 형식의 배열이어야 한다)


jQuery("#list").setRowData( "1", { tax:"5", total:"205" });
id가 1인 row의 tax, total 값을 변경하며 성공시 true, 그외 false를 반환한다.



 - 데이터 업데이트
그리드 row들을 한번에 업데이트 하려면 updateGridRows를 사용하면 된다.
(링크의 애드온메소드 참고)







Function

 - 이 옵션은 모든 datatype에 대해 실제로 정의하는게 아니라 서버에서 받은 xml 또는 json 데이터를 다루는 방식이다.
이 함수는 전달받은 데이터에 대해서 addXMLData 또는 addJSONData 또는 addRowData를 호출하는 datatype에 대해서 정의한다.
Pager를 사용하는경우 your_grid.setGridParam({lastpage: your_number}) 로 페이지의 번호를 지정하는데 유용하다.

datatype : function(postdata) {
// do something here
}

datatype 함수는 일반적으로 GET 또는 POST 파라메터로 전환된 request 정보가 포함된 단일 객체가 제공된다.
이 객체는 jQuery의 $.ajax 함수에서 제공하는 data:option 과 호환이 된다.

<script type="text/javascript">
...
jQuery(document).ready(function(){ 
  jQuery("#list").jqGrid({
    datatype: function(postdata) {
        jQuery.ajax({
           url: 'example.php',
           data:postdata,
           dataType:"xml",
           complete: function(xmldata,stat){
              if(stat=="success") {
                 var thegrid = jQuery("#list")[0];
                 thegrid.addXmlData(xmldata.responseXML);
              }
           }
        });
    },
    colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],
    colModel :[ 
      {name:'invid', index:'invid', width:55}, 
      {name:'invdate', index:'invdate', width:90}, 
      {name:'amount', index:'amount', width:80, align:'right'}, 
      {name:'tax', index:'tax', width:80, align:'right'}, 
      {name:'total', index:'total', width:80, align:'right'}, 
      {name:'note', index:'note', width:150, sortable:false} 
    ],
    pager: '#pager',
    rowNum:10,
    rowList:[10,20,30],
    sortname: 'invid',
    sortorder: 'desc',
    viewrecords: true,
    caption: 'My first grid'
  }); 
}); 
...
</script>





User Data

 - 어떤 경우에는 jqGrid가 자동으로 보여주지 않는 request의 커스텀 데이터가 있을수도 있으며, 나중에 프로세스에서 사용되거나 그리드와 연관된 또는 HTML에 정보를 표시해야 할 수도 있는데 이를 위해서 userdata를 사용할 수 있다.


xmlReader: {
  ...
  userdata: "userdata",
  ...
}
xmlReader의 경우에는 위와 같이 선언하고, 아래와 같이 서버에서 받은 정보의 XML태그에 name 속성이 있어야 데이터 연결이 가능하다.
<invoices>  
    <request>true</request>  
    <userdata name="totalinvoice"> 240.00 </userdata>  
    <userdata name="tax"> 40.00</userdata>
    ... 
    <result>  
      <row>  
        <cell>data1</cell>
        <cell>data2</cell>
        <cell>data3</cell>
        <cell>data4</cell>
        <cell>data5</cell>
        <cell>data6</cell>
      </row>
      ... 
    </result> 
</invoices>

1004lucifer

jsonReader: {
  ...
  userdata: "userdata",
  ...
}
json 데이터의 경우에는 위와같이 선언하고, 아래와 같이 배열 옵션의 userData 안에 정보를 저장한다.
{ 
  total: "xxx", 
  page: "yyy", 
  records: "zzz", 
  userData: {totalinvoice:240.00, tax:40.00}, 
  rows : [ 
    {id:"1", cell:["cell11", "cell12", "cell13"]}, 
    {id:"2", cell:["cell21", "cell22", "cell23"]}, 
    ... 
  ] 
}


데이터는 아래의 Old, New두가지 방법으로 가져올 수 있다.

jQuery("grid_id").jqGrid('getGridParam', 'userData')
jQuery("grid_id").getGridParam('userData')



참고
 - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data

댓글