티스토리 뷰

Cell Renderer & Style & Drop Down 설정 예제 

값을 받아서 보여줄 때 가공을 해야 하는 경우가 있습니다. 

코드인 경우 코드의 값으로 전환해야 하고 필요한 경우 그래프나 아이콘, 이미지 등으로 보여 줘야 할 때도 있습니다. 

그런 경우 cellRenderer를 이용해서 표현할 수 있습니다. 

예제코드로는 세가지를 확인해 볼 수 있습니다. 

1. cell에 스타일 적용하기. 

- 정렬 또는 background color 등을 지정할 수 있습니다. 

2. data renderering

- 숫자는 오른쪽 정렬을 해야 하며 세자리 마다 콤마를 찍어 줘야 합니다.  

- Style, Use는 코드 값을 받으며 Value로 표현해야 합니다. 

3. Data 편집시 drop down 박스 처리 (중요)

- 여기서는 단순히 표현에 대한 것만 예제로 만들었습니다. 

- ag-grid나 다른 곳에 관련 소스를 찾기가 어려워 많이 고생을 했던거 같습니다. 

- Use를 클릭하면 drop down박스에 value를 보여 주고 code로 저장이 되어야 합니다. 

cellEditorParams, valueFormatter, valueParser, cellRenderer 네가지 설정이 필요합니다.

- 이 부분은 실무 적용 시 부딛치는 문제라 나중에 적용시 확인하실 수 있습니다.  

 

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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>AG GRID Renderer & SelectCellEditor & CellStyle</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 Renderer & SelectCellEditor & CellStyle</h2>
    <div class="grid-wrapper">
        <div style="width: 100%; height:380px" id="myGrid" class="ag-grid-div ag-theme-balham ag-basic"></div>
    </div>
</div>
  <script>
  var styleCodes = function(){
      var codes = [];
      codes[0= new NameValue("S""Smooth");
      codes[1= new NameValue("F""Filthy");
      codes[2= new NameValue("D""Shorts");
      return codes;
  };
  var useYNCodes = function(){
      var codes = [];
      codes[0= new NameValue("Y""Use");
      codes[1= new NameValue("N""Not use");
      return codes;
  };
 
  var MainGrid = function(){
        var _this = this;
        /* grid 영역 정의 */
        this.gridDiv = "myGrid";
        /* grid 칼럼 정의 */
        this.getColumnDefs = function(){
            var columnDefs = [
                {headerName: "Make", field: "make", cellStyle:{"textAlign":"left"'background-color''#f1f7ff'}},
                {headerName: "Model", field: "model"},
                {headerName: "Price", field: "price", cellStyle:{"textAlign":"right"}, cellRenderer : CommonGrid.formatCurrency},
                {headerName: "Zombies", field: "zombies"},
                {headerName: "Style", field: "style", cellRenderer : _this.convertStyle},
                {headerName: "Clothes", field: "clothes"},
                {headerName : "Use", field:"useYn", width:70, minWidth:70, editable:true, cellEditor:'agSelectCellEditor'
                        cellEditorParams: {values : extractValues(useYNCodes())}, 
                        valueFormatterfunction (params) {
                            return lookupValue(useYNCodes(), params.value);
                        },
                        valueParserfunction (params) {
                            return lookupKey(useYNCodes(), params.newValue);
                        },
                        cellRenderer:_this.convertUseYn, cellStyle:{"textAlign":"center"}}
 
            ];
            var gridOpt = CommonGrid.getDefaultGridOpt(columnDefs);
            //gridOpt.onRowClicked = onRowClicked;
            return gridOpt;
        };
        /* grid 옵션 가져오기 */
        this.gridOpts = null
        /* grid 실행 */
        this.makeGrid = function(rowData){
            _this.gridOpts = _this.getColumnDefs();
            CommonGrid.makeGridCommon(_this.gridDiv, _this.gridOpts, rowData)
        };
        this.convertStyle = function(node){
            return getCodeValue(styleCodes(), node);
        };
        this.convertUseYn = function(node){
            return getCodeValue(useYNCodes(), node);
        }
    }
    var mainGrid = new MainGrid();
 
    // setup the grid after the page has finished loading
    document.addEventListener('DOMContentLoaded'function() {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET''./testData.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
[
    {
        "make" : "Toyota",
        "model""Celica",
        "price"35000,
        "zombies""Elly",
        "style""S",
        "clothes""Jeans",
        "useYn""Y",
        "date":"2019/01/29"
    },
    {
        "make""Ford",
        "model""Mondeo",
        "price"32000,
        "zombies""Shane",
        "style""F",
        "clothes""Shorts",
        "useYn""N",
        "date":"2019/01/27"
    },
    {
        "make""Porsche",
        "model""Boxter",
        "price"72000,
        "zombies""Jack",
        "style""D",
        "clothes""Padded",
        "useYn""Y",
        "date":"2019/01/28"
    }
]
 
cs

 

Util js

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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/**
* AG-GRID COMMON UTILS
* @author kkaok, kkaok.pe.kr@gmail.com
*/
/**
 * currency 표현. 세자리 마다 콤마
 */
Number.prototype.format = function(n, x) {
    var re = '\\d(?=(\\d{' + (x || 3+ '})+' + (n > 0 ? '\\.' : '$'+ ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};
 
/**
 * NameValue Object
 */
var NameValue = function (pname, pvalue){
    this.name = pname;
    this.value = pvalue;
}
/**
 * cellRenderer 등에서 사용하기 위한 것으로 
 * 배열로 코드를 받아서 node의 값과 일치하는 value를 반환한다. 
 */
var getCodeValue = function(codes, nodeData){
    if(!codes) return " - ";
    for(var i=0;i<codes.length;i++){
        if(nodeData.value == codes[i].name){
            return codes[i].value;
        }
    }
    return " - ";
}
 
/**
 * 콤보박스 처리 
 * 객체에서 key값 추출하는 함수
 * var data = {
 *     headerName : "월",
 *     field : "mon",
 *     width : 100,
 *     editable : true,
 *     cellEditor : 'agSelectCellEditor',
 *     cellStyle : {
 *         "textAlign" : "center"
 *     },
 *     cellRenderer : CommonGrid.convertLeadTime,
 *     cellEditorParams : {
 *         values : extractValues(CommonCode.leadTimeCodes())
 *     },
 *     valueFormatter : function(params) {
 *         return lookupValue(CommonCode.leadTimeCodes(), params.value);
 *     },
 *     valueParser : function(params) {
 *         return lookupKey(CommonCode.leadTimeCodes(), params.newValue);
 *     }
 * }
 */
function extractValues(mappings) {
    var params = new Array();
    for (var i = 0; i< mappings.length;i++) {
        params.push(mappings[i].name);
    }
    return params;
}
 
/**
 * 객체에서 key로 value을 반환하는 함수, 콤보박스에서 사용
 */
function lookupValue(mappings, key) {
    for (var i = 0; i< mappings.length;i++) {
        if (mappings[i].name == key) {
            return mappings[i].value;
        }    
    }
    return "";
}
 
/**
 * 객체에서 vaue로 key를 반환하는 함수, 콤보박스에서 사용
 */
function lookupKey(mappings, name) {
    for (var i = 0; i< mappings.length;i++) {
        if (mappings[i].value == name) {
            return mappings[i].name;
        }    
    }
    return "";
}
 
/**
 * Date Picker 사용법 
 * 1. 칼럼 정의 시 editable : true, cellEditor : 'datePicker' 추가 
 * 2. 칼럼옵션에 컴포넌트 추가 
 * gridOpt.components = {
 *  datePicker: getDatePicker('yy-mm-dd') // date format 지정시 포맷 전달 
 *  datePicker: getDatePicker()  // 기본은 yymmdd 8자리로 됨 
 * };
 */
function getDatePicker(paramFmt) {
    var _this = this;
    _this.fmt = "yymmdd";
    if(paramFmt){
        _this.fmt = paramFmt;
    }
    // function to act as a class
    function Datepicker() {}
 
    // gets called once before the renderer is used
    Datepicker.prototype.init = function(params) {
        // create the cell
        this.eInput = document.createElement('input');
        this.eInput.value = params.value;
 
        // https://jqueryui.com/datepicker/
        $(this.eInput).datepicker({
            dateFormat: _this.fmt
        });
    };
 
    // gets called once when grid ready to insert the element
    Datepicker.prototype.getGui = function() {
        return this.eInput;
    };
 
    // focus and select can be done after the gui is attached
    Datepicker.prototype.afterGuiAttached = function() {
        this.eInput.focus();
        this.eInput.select();
    };
 
    // returns the new value after editing
    Datepicker.prototype.getValue = function() {
        return this.eInput.value;
    };
 
    // any cleanup we need to be done here
    Datepicker.prototype.destroy = function() {
        // but this example is simple, no cleanup, we could
        // even leave this method out as it's optional
    };
 
    // if true, then this editor will appear in a popup
    Datepicker.prototype.isPopup = function() {
        // and we could leave this method out also, false is the default
        return false;
    };
 
    return Datepicker;
}
/**
 * 공통 그리드 util
 */
var CommonGrid = {
        defaultBlank : " - "
        // csv 파일 export    
        ,onBtExport : function(title, gridOpts){
            var params = {
                    skipHeader: false,
                    skipFooters: false,
                    columnGroups: true,
                    skipGroups: false,
                    skipPinnedTop: false,
                    skipPinnedBottom: false,
                    allColumns: true,
                    onlySelected: false,
                    fileName: title + moment().format("YYYYMMDDHHmmss")+ '.csv'
            };
            gridOpts.api.exportDataAsCsv(params);
        }
        // 칼럼정의 값으로 기본 grid option을 생성한다.      
        ,getDefaultGridOpt : function(pColumnDefs) {
            return this.getDefaultGridOptResize(pColumnDefs, true);
        }
        // 칼럼정의 값으로 기본 grid option을 생성한다. 리사이즈 안함.       
        ,getDefaultGridOptNoResize : function(pColumnDefs) {
            return this.getDefaultGridOptResize(pColumnDefs, false);
        }
        // 칼럼정의 값으로 기본 grid option을 생성한다.      
        ,getDefaultGridOptResize : function(pColumnDefs,autosize) {
            return {
                columnDefs: pColumnDefs,
                rowSelection: 'single'/* 'single' or 'multiple',*/
                enableColResize: true,
                enableSorting: true,
                enableFilter: true,
                enableRangeSelection: true,
                suppressRowClickSelection: false,
                animateRows: true,
                suppressHorizontalScroll: false,
                localeText: {noRowsToShow: '조회 결과가 없습니다.'},
                getRowStyle: function (param) {
                    if (param.node.rowPinned) {
                        return {'font-weight''bold', background: '#dddddd'};
                    }
                    return {'text-align''center'};
                },
                getRowHeight: function(param) {
                    if (param.node.rowPinned) {
                        return 30;
                    }
                    return 30;
                },
                // 리사이즈 
                onGridReady: function(params) {
                    params.api.sizeColumnsToFit();
                },
                // 창 크기 변경 되었을 때 이벤트 
                onGridSizeChanged: function(params) {
                    params.api.sizeColumnsToFit();
                },
                debug: false
            };
        }
        // 그리드 값 넣기 
        ,makeGridCommon : function (gridDiv, pGridOpts, rowData){
            $('#'+gridDiv).children().remove();
            var eGridDiv = document.querySelector('#'+gridDiv);
            new agGrid.Grid(eGridDiv, pGridOpts);
            pGridOpts.api.setRowData(rowData);
        }
        ,convertTime : function (param){
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(param.value, "YYYYMMDDHHmmss").format("HH:mm");
            }
        }
        ,convertDate : function(param) { // 8자리 문자열을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else{
                if(param.value.length ==8) {
                    return moment(param.value, "YYYYMMDD").format("YYYY-MM-DD");
                }else{
                    return param.value;
                }
            }        
        }
        ,convertTimestamp : function(param) { // 8자리 문자열을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(param.value, "YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss");
            }        
        }
        ,formatDate : function(param) { // long 값을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(parseInt(param.value)).format("YYYY-MM-DD");
            }        
        }
        ,formatTimestamp : function(param) { // long 값을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(parseInt(param.value)).format("YYYY-MM-DD HH:mm:ss");
            }        
        }
        ,numberOnly : function(param){ 
            if(!param.value || param.value ==''return '';
            if (typeof param.value === 'string') {
                return param.value.replace(/[^0-9\.]+/g, '');
            }
            return CommonGrid.formatCurrency(param);
        }
        ,formatCurrency : function (param){
            if(!param.value && param.value != "0") {
                return this.defaultBlank;
            }    
            return parseInt(param.value).format();
        }
        ,formatNumber : function(param){
            if(!param.value && param.value != "0") {
                return this.defaultBlank;
            }    
            return numberFormatPoint2Digits(param.value);
        }
        ,convertCommon : function(codes, param){
            if(!codes) return " - ";
            for(var i=0;i<codes.length;i++){
                if(param.value == codes[i].name){
                    return codes[i].value;
                }
            }
            return this.defaultBlank;
        }
        ,getCode : function(codes, value){
            for(var i=0;i<codes.length;i++){
                if(value == codes[i].value){
                    return codes[i].name;
                }
            }
            return "";
        }
        ,checkMobile : function(gridOpts){
            // 모바일 브라우저 가로크기 체크
            if (document.body.clientWidth < 800) {
                if(gridOpts){
                    gridOpts.columnDefs.forEach(function(el) {
                        el.pinned = null;
                        if(el.children){
                            el.children.forEach(function(subEl) {
                                subEl.pinned = null;
                            });
                        }
                    });
                }
            }
        }
        ,makeTopGrid : function(gridMainOpts, rowData, params){
            var colsSum = [];
            gridMainOpts.columnDefs.forEach(function(coldefs, index) {
                if(coldefs.children){
                    coldefs.children.forEach(function(child, index) {
                        if(child.isSum && child.isSum == true){
                            var temp = {};
                            temp[child.field] = 0;
                            temp["field"= child.field;
                            colsSum.push(temp);
                        }
                    });
                }else{
                    if(coldefs.isSum && coldefs.isSum == true){
                        var temp = {};
                        temp[coldefs.field] = 0;
                        temp["field"= coldefs.field;
                        colsSum.push(temp);
                    }
                }
            });
            rowData.forEach(function(rowvalue, index) {
                colsSum.forEach(function(value, index) {
                     if(rowvalue[value.field] && !rowvalue[value.field].isNaN)
                         value[value.field] += rowvalue[value.field];
                });
            });
             var resultSum = {}
             colsSum.forEach(function(cValue, index) {
                 resultSum[cValue.field] = cValue[cValue.field];
 
            });
             if(params && params.length>0){
                 params.forEach(function(value, index) {
                     resultSum[value.field] = value.value;
                });
             }
             resultSum['top'= true;
            var resultArray = [];
            resultArray[0= resultSum;
            gridMainOpts.api.setPinnedTopRowData(resultArray);
        }
    }
cs


파일 첨부 

cellRenderer.zip


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

AG-GRID 필터와 정렬 예제  (0) 2019.01.30
AG-GRID Data 선택 이벤트 처리 예제  (0) 2019.01.30
AG-GRID 기본 예제  (0) 2019.01.30
AG-GRID GRID OPTIONS 정의  (3) 2019.01.30
AG-GRID 칼럼 정의  (1) 2019.01.30
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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
글 보관함