jqGrid에서 서브그리드 구현 방법

서브그리드 이벤트 핸들링

jqGrid의 서브그리드 기능 구현 시 주요 이벤트:

  • subGridRowExpanded: '+' 아이콘 클릭 시 발동. 자동 생성된 div 엘리먼트의 ID와 행 ID 획득 가능
  • subGridRowColapsed: '-' 아이콘 클릭 시 발동. 서브그리드 div 자동 제거
  • 사용자 정의 동작 구현 가능 (예: 서브그리드 대체 기능)

기본 그리드 설정

<div class="container">
  <table id="mainGrid"></table>
  <div id="gridPager"></div>
</div>

<script>
$(document).ready(initGrid);

function initGrid() {
  $("#mainGrid").jqGrid({
    height: 450,
    url: "data/products",
    datatype: "json",
    colNames: ['ID','제품명','설명','가격','활성화'],
    colModel: [
      { name: 'prodId', width: 60 },
      { name: 'title', width: 120 },
      { name: 'description', width: 200 },
      { name: 'price', width: 80 },
      { name: 'isActive', formatter: statusFormatter }
    ],
    pager: '#gridPager',
    subGrid: true,
    subGridRowExpanded: function(subgridId, rowId) {
      initSubGrid(subgridId, rowId);
    }
  });
}
</script>

서브그리드 초기화

function initSubGrid(subgridId, parentId) {
  const tableId = subgridId + "_table";
  const pagerId = subgridId + "_pager";
  
  $("#" + subgridId).html(
    `<table id="${tableId}"></table><div id="${pagerId}"></div>`
  );

  $("#" + tableId).jqGrid({
    url: `data/productDetails/${parentId}`,
    datatype: "json",
    colModel: [
      { name: 'detailId', key: true },
      { name: 'image', formatter: imageRenderer },
      { name: 'spec', width: 150 },
      { name: 'quantity', width: 70 }
    ],
    gridComplete: function() {
      const rowIDs = $(this).jqGrid('getDataIDs');
      rowIDs.forEach(id => {
        const actionBtns = `
          <div class="btn-group">
            <button onclick="modifyItem('${tableId}',${id})">수정</button>
            <button onclick="removeItem('${tableId}',${id})">삭제</button>
          </div>`;
        $(this).jqGrid('setRowData', id, { actions: actionBtns });
      });
    }
  });
}

항목 삭제 처리

function removeItem(tableRef, itemId) {
  if(confirm("정말 삭제하시겠습니까?")) {
    $.ajax({
      type: 'DELETE',
      url: `api/items/${itemId}`,
      success: () => {
        $(`#${tableRef}`).trigger("reloadGrid");
      }
    });
  }
}

tableRef 매개변수는 HTMLTableElement 객체 전달되며, 실제 테이블 ID는 tableRef.id로 접근

태그: jqGrid 서브그리드 JavaScript jQuery 데이터테이블

5월 29일 02:33에 게시됨