티스토리 뷰

UI(Front-End)/그리드

AG-GRID 추가/수정/삭제 예제

까오기 까오기 2019. 1. 30. 15:24

AG-GRID 추가/수정/삭제 예제

예제에서 확인 할 내용

1. 체크박스, 체크박스 전체 선택 및 해제

- 코드를 통해 알 수있다. 

2. 편집모드에서 시작, 종료 이벤트 처리 

- 종료시 변경 데이터를 별도로 저장해 두었다가 저장 시점에 변경된 데이터만 서버에 전송할 필요가 있다.  

3. 삭제 처리 

4. 편집모드 강제 종료 하기

- 편집모드에서 바로 저장, 수정 등의 버튼을 클릭하면 변경 사항이 적용이 안되는데 이때 강제 종료 시키면 해결이 된다.

5. 버튼을 통한 편집모드 이동. 

6. 첫번째, 마지막에 ROW 추가하기 

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>AG GRID CUD</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
  <script src="https://unpkg.com/ag-grid/dist/ag-grid.min.js"></script>
  <script src="/assets/js/agGridUtil.js"></script>
</head>
<body>
<div class="container">
    <h2>AG GRID CUD</h2>
    <small>Russia는 선택 안됨</small>
    <div style="padding: 2px;">
        <button onclick="onBtSelectAll()">전체선택</button>
        <button onclick="onBtDeselectAll()">선택취소</button>
        <button onclick="onBtDelete()">선택삭제</button>
        &nbsp;
        <button onclick="onBtStopEditing()">stop ()</button>
        <button onclick="onBtNextCell()">next ()</button>
        <button onclick="onBtPreviousCell()">previous ()</button>
        &nbsp;
        <button onclick="onBtSave()">변경데이터</button>
        <button onclick="onBtAddTop()">첫번째 추가</button>
        <button onclick="onBtAddBottom()">마지막 추가</button>
    </div>
    <div id="updateRows" style="height:100px;border:1px solid #f4f4f4;margin:5px 0"></div>
    <div class="grid-wrapper">
        <div style="width: 100%; height:580px" id="myGrid" class="ag-grid-div ag-theme-balham ag-basic"></div>
    </div>
</div>
  <script>
  var MainGrid = function(){
        var _this = this;
        /* grid 영역 정의 */
        this.gridDiv = "myGrid";
        /* grid 칼럼 정의 */
        this.getColumnDefs = function(){
            var columnDefs = [
                {checkboxSelection: true},
                {field: "athlete", width: 150, suppressSizeToFit: true, editable: true},
                {field: "age", width: 90, minWidth: 50, maxWidth: 100, editable: true},
                {field: "country", width: 120, editable: true},
                {field: "year", width: 90, editable: true},
                {field: "date", width: 110, editable: true},
                {field: "sport", width: 110, editable: true},
                {field: "gold", width: 100, editable: true},
                {field: "silver", width: 100, editable: true},
                {field: "bronze", width: 100, editable: true},
                {field: "total", width: 100, editable: true}
            ];
            var gridOpt = CommonGrid.getDefaultGridOpt(columnDefs);
            gridOpt.rowSelection = 'multiple';
            gridOpt.isRowSelectable = function(rowNode){
                return (rowNode.data.country != "Russia")? true:false;
            }
            gridOpt.onRowEditingStarted = function(event) {
                console.log('never called - not doing row editing');
            };
            gridOpt.onRowEditingStopped = function(event) {
                console.log('never called - not doing row editing');
            };
            gridOpt.onCellEditingStarted = function(event) {
                console.log('cellEditingStarted');
            };
            gridOpt.onCellEditingStopped = function(event) {
                console.log('cellEditingStopped');
                event.data.edit = true;
                gridOpt.api.updateRowData({update: [event.data]});
                console.log(gridOpt.api.getDisplayedRowAtIndex(event.rowIndex).data);               
            };
            
            return gridOpt;
        };
        /* grid 옵션 가져오기 */
        this.gridOpts = null
        /* grid 실행 */
        this.makeGrid = function(rowData){
            _this.gridOpts = _this.getColumnDefs();
            CommonGrid.makeGridCommon(_this.gridDiv, _this.gridOpts, rowData)
        };
        this.getRowIndex = function(node){
            return node.rowIndex+1;
        }
    }
    var mainGrid = new MainGrid();
 
    function onBtStopEditing() {
        mainGrid.gridOpts.api.stopEditing();
    }
    function onBtNextCell() {
        mainGrid.gridOpts.api.tabToNextCell();
    }
    function onBtPreviousCell() {
        mainGrid.gridOpts.api.tabToPreviousCell();
    }
    var removedRows = [];
    function onBtDelete() {
        var selectedRows = mainGrid.gridOpts.api.getSelectedRows();
        selectedRows.forEach( function(selectedRow, index) {
            removedRows.push(selectedRow);
            mainGrid.gridOpts.api.updateRowData({remove: [selectedRow]});
        });
    }
    var updateRows = [];
    function onBtSave() {
        mainGrid.gridOpts.api.stopEditing();
        mainGrid.gridOpts.api.forEachNode( function(rowNode, index) {
            if(rowNode.data.edit){
                updateRows.push(rowNode.data);
            }
        });
        $("#updateRows").html(JSON.stringify(updateRows));
    }
    function onBtSelectAll() {
        mainGrid.gridOpts.api.selectAll();
    }
    function onBtDeselectAll() {
        mainGrid.gridOpts.api.deselectAll();
    }
    var newRow = {
            seq : null,
            athlete : '',
            age : null,
            year : '',
            date : '',
            sport : '',
            gold : null,
            silver : null,
            bronze : null,
            total : null 
    }
    function onBtAddTop() {
        mainGrid.gridOpts.api.updateRowData({add: [newRow], addIndex:0});
    }
    function onBtAddBottom() {
        mainGrid.gridOpts.api.updateRowData({add: [newRow]});
    }
 
    // setup the grid after the page has finished loading
    document.addEventListener('DOMContentLoaded'function() {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET''./olympicWinnersSmall.json');
        httpRequest.send();
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                var httpResult = JSON.parse(httpRequest.responseText);
                mainGrid.makeGrid(httpResult);
            }
        };
    });  
  </script>
</body>
</html>
cs

Json data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[
    {
        "athlete": "Michael Phelps",
        "age": 23,
        "country": "United States",
        "year": 2008,
        "date": "24/08/2008",
        "sport": "Swimming",
        "gold": 8,
        "silver": 0,
        "bronze": 0,
        "total": 8
    },
    {
        "athlete": "Michael Phelps",
        "age": 19,
        "country": "United States",
        "year": 2004,
        "date": "29/08/2004",
        "sport": "Swimming",
        "gold": 6,
        "silver": 0,
        "bronze": 2,
        "total": 8
    },
    {
        "athlete": "Michael Phelps",
        "age": 27,
        "country": "United States",
        "year": 2012,
        "date": "12/08/2012",
        "sport": "Swimming",
        "gold": 4,
        "silver": 2,
        "bronze": 0,
        "total": 6
    }
]
cs

파일 첨부

CUDExample.zip


'UI(Front-End) > 그리드' 카테고리의 다른 글

AG-GRID 칼럼 동적 HIDE/SHOW 예제  (0) 2019.01.30
AG-GRID Datepicker 예제  (0) 2019.01.30
AG-GRID 추가/수정/삭제 예제  (1) 2019.01.30
AG-GRID 필터와 정렬 예제  (0) 2019.01.30
AG-GRID Data 선택 이벤트 처리 예제  (0) 2019.01.30
AG-GRID cellRenderer 예제  (4) 2019.01.30
댓글
  • 프로필사진 Leader 혹시 이거 CSV 파일 저장하는 함수가 들어있던데 어떻게 호출해서 사용하는지 좀 알려주실 수 있을까요? 2020.07.02 17:27
댓글쓰기 폼