ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Salesforce Developer] lightning-datatable
    Salesforce 2025. 2. 28. 20:29

    lightning-datatable

    • 화면 개발 시, lwc에서 기본 제공해주는 데이터 테이블

     

    기본 소스코드 및 속성

    // HTML
    <template>
        <div>
            <lightning-datatable
                    key-field="id"
                    data={data}
                    columns={columns}
                    show-row-number-column	// row의 번호를 붙이는 설정
                    hide-checkbox-column	// row의 checkbox를 추가하는 설정
                    >
            </lightning-datatable>
        </div>
    </template>
    
    // JS
    import { LightningElement } from 'lwc';
    
    // 드롭다운 버튼의 Actions List
    const actions = [
        { label: 'Show details', name: 'show_details' },
        { label: 'Delete', name: 'delete' },
    ];
    
    const columns = [
        { label: 'Label', fieldName: 'name' , editable: true}, // editable: true 설정한 column은 수정이 가능
        { label: 'Website', fieldName: 'website', type: 'url', cellAttributes: {class: 'slds-text-color_success slds-text-title_caps',},}, //cellAttributes는 해당 Cell의 속성을 부여해주는 설정으로 아이콘 등도 설정이 가능하다.
        { label: 'Phone', fieldName: 'phone', type: 'phone', sortable: true }, // sortable: true로 설정한 column은 정렬이 가능하다. (기본은 false)
        { label: 'Balance', fieldName: 'amount', type: 'currency', typeAttributes: { currencyCode: 'EUR' }, }, // typeAttributes은 데이터 유형의 속성을 custom으로 지정해주는 설정
        { label: 'CloseAt', fieldName: 'closeAt', type: 'date' },
        /*
        드롭다운 버튼을 추가하는 속성
        {
            type: 'action',
            typeAttributes: { rowActions: actions }, 
        },
        */
    ];
    
    export default class BasicDatatable extends LightningElement {
        data = [
        {name : 'Name(0)', website: 'www.salesforce.com',amount: 1, phone:000-0000-0000, closeAt:Date.now()}
        ,{name : 'Name(1)', website: 'www.salesforce.com',amount: 1, phone:000-0000-0000, closeAt:Date.now()}
        ,{name : 'Name(2)', website: 'www.salesforce.com',amount: 1, phone:000-0000-0000, closeAt:Date.now()}
        ,{name : 'Name(3)', website: 'www.salesforce.com',amount: 1, phone:000-0000-0000, closeAt:Date.now()}
        ];
        columns = columns;
        
        constructor() {
            super();
            this.columns = [
                // Other column skip...
                // Dynamic Action 설정
                { type: 'action', typeAttributes: { rowActions: this.getRowActions } },
            ]
        }
    
        getRowActions(row, doneCallback) {
        const actions = [];
            if (row['isActive']) {
                actions.push({
                    'label': 'Deactivate',
                    'iconName': 'utility:block_visitor',
                    'name': 'deactivate'
                });
            } else {
                actions.push({
                    'label': 'Activate',
                    'iconName': 'utility:adduser',
                    'name': 'activate'
                });
            }
            // simulate a trip to the server
            setTimeout(() => {
                doneCallback(actions);
            }), 200);
        }
    }

     

    datatable의 에러처리

    // HTML
    <template>
        <lightning-datatable
            key-field="id"
            data={data}
            columns={columns}
            errors={errors}>
        </lightning-datatable>
    </template>
    
    // JS
    import { LightningElement } from 'lwc';
    import generateData from './generateData';
    
    // Add <datatable-with-errors></datatable-with-errors> to the lwr-playground to see the table
    
    const columns = [
        { label: 'Label', fieldName: 'name', editable: true },
        { label: 'Website', fieldName: 'website', type: 'url', editable: true },
        { label: 'Phone', fieldName: 'phone', type: 'phone', editable: true },
        { label: 'Balance', fieldName: 'amount', type: 'currency' },
        { label: 'CloseAt', fieldName: 'closeAt', type: 'date', editable: true },
    ];
    
    export default class DatatableWithError extends LightningElement {
        data = [
        {name : 'Name(0)', website: 'www.salesforce.com',amount: 1, phone:000-0000-0000, closeAt:Date.now()}
        ,{name : 'Name(1)', website: 'www.salesforce.com',amount: 1, phone:000-0000-0000, closeAt:Date.now()}
        ,{name : 'Name(2)', website: 'www.salesforce.com',amount: 1, phone:000-0000-0000, closeAt:Date.now()}
        ];
        columns = columns;
        errors = {};
    
        connectedCallback() {
            // error 발생 Code
            this.handleError();
        }
    
        handleError() {
            this.errors = {
                rows: {
                    1: {
                        title: 'We found 2 errors.',
                        messages: [
                            'Enter a valid name',
                            'Verify the phone number and try again.',
                        ],
                        fieldNames: ['name', 'phone'],
                    },
                },
                table: {
                    title: 'Your entry cannot be saved. Fix the errors and try again.',
                    messages: [
                        'Row 1 name must be valid text',
                        'Row 1 phone number is invalid',
                    ],
                },
            };
        }
    }

     

    datatable의 자주쓰는 Action 함수

    <lightning-datatable
        data={data}
        columns={columns}
        key-field="Id"
        onrowselection={handleRowSelection}	// row의 체크박스 클릭 시, 발생
        oncellchange={handleCellChange}		// editable:true일 경우, 값이 변경되면 발생
        onclick={handleClick}				// cell을 클릭하면 발생
    >
    
    
    // row data 관련 Action
    handleRowSelection(event) {
        switch (event.detail.config.action) {
            case 'selectAllRows':
                break;
            case 'deselectAllRows':
                break;
            case 'rowSelect':
                break;
            case 'rowDeselect':
                break;
            default:
                break;
        }
    }
    
    handleCellChange() {
    
    }
    
    handleClick() {
    
    }

     

    Tip

    특정 cell만 수정 가능하게 하고 싶다면, 해당 html의 class를 찾아서 display : none; css를 부여하면 동적으로 수정할 부분을 조정할 수 있다.

     

     

    출처)

    https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/example

Designed by Tistory.