前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Salesforce Lightning Data Table With Row Actions(二)

Salesforce Lightning Data Table With Row Actions(二)

原创
作者头像
repick
发布2022-05-10 22:13:33
6200
发布2022-05-10 22:13:33
举报
文章被收录于专栏:SalesforceSalesforce

下边做成删除子画面,编辑子画面,分别进行消除和编辑操作,如下,点击Edit时,打开编辑子画面进行数据更新,点击Delete时,打开消除子画面进行数据消除。

1.删除子画面

relatedListRecordDelete.html

代码语言:javascript
复制
<template>
    <template if:true={showDeleteDilog}>
        <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <header class="slds-modal__header">
                    <h2 id="modal-heading-02" class="slds-text-heading_medium slds-hyphenate">{objectLabel}を削除</h2>
                    <lightning-button-icon class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse"
                        icon-name="utility:close" alternative-text="close" title="close" onclick={handleCancel}>
                    </lightning-button-icon>
                </header>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-3">
                    この{objectLabel}を削除しますか?
                </div>
                <footer class="slds-modal__footer">
                    <button class="slds-button slds-button_neutral" onclick={handleCancel}>キャンセル</button>
                    <button class="slds-button slds-button_brand" onclick={handleDelete}>削除</button>
                </footer>
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </template>
</template>

relatedListRecordDelete.js

代码语言:javascript
复制
import { LightningElement, api, track } from 'lwc';
import { deleteRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class RelatedListRecordDelete extends LightningElement {
    @api recordId;
    @api objectLabel;
    @api showDeleteDilog

    @track error;
    handleDelete(event) {
        deleteRecord(this.recordId)
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Record deleted',
                        variant: 'success'
                    })
                );
                this.dispatchEvent(new CustomEvent('deletesuccess'));
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error deleting record',
                        message: error.body.message,
                        variant: 'error'
                    })
                );
            });
    }

    handleCancel() {
        this.dispatchEvent(new CustomEvent('deletecancel'));
    }
}

2.编辑子画面

relatedListRecordEdit.html

代码语言:javascript
复制
<template>
    <template if:true={showEditDilog}>
        <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <header class="slds-modal__header">
                    <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">{recordName}を編集</h2>
                    <lightning-button-icon class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse"
                        icon-name="utility:close" alternative-text="close" title="close" onclick={handleCancel}>
                    </lightning-button-icon>
                </header>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-2">
                    <lightning-record-form
                        record-id={recordId}
                        layout-type="Full"
                        object-api-name={objectApiName}
                        mode="edit"
                        onsuccess={handleSuccess}
                        oncancel={handleCancel}>
                    </lightning-record-form>
                </div>
                <footer class="slds-modal__footer"></footer>
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </template>
</template>

relatedListRecordEdit.js

代码语言:javascript
复制
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class RelatedListRecordEdit extends LightningElement {
    @api recordId;
    @api recordName;
    @api objectApiName;
    @api showEditDilog;

    handleCancel() {
        this.dispatchEvent(new CustomEvent('closeedit'));
    }

    handleSuccess() {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: this.objectApiName + ' Updated',
                variant: 'success'
            })
        );
        this.dispatchEvent(new CustomEvent('updatesuccess'));
    }
}

3.主Lwc的html中调用子画面

basicDatatable.html

代码语言:javascript
复制
<template>
    <div style="background-color: white; border-bottom-style:double;">
        <lightning-layout multiple-rows="true" horizontal-align="center" vertical-align="center">
            <lightning-layout-item padding="around-small" size="5" style="position: absolute; left: 0%;">
                <span class="slds-var-p-right_x-small" style="font-size: 16px; font-weight: bold;">担当者</span>
                <span class="slds-var-p-right_x-small" style="font-size: 32px; font-weight: bold;">{recordLength}</span>
                <span class="slds-var-p-right_x-small" style="font-size: 16px; font-weight: bold;">件</span>
            </lightning-layout-item>
            <lightning-layout-item padding="around-small" size="2">
                <span>&nbsp;</span>
            </lightning-layout-item>
            <!-- <lightning-layout-item padding="around-small" size="2" style="position: absolute; left: 65%;">
                <span style="font-size: 16px;">最終更新:数秒前</span>
            </lightning-layout-item> -->
            <lightning-layout-item padding="around-small" size="5" style="position: absolute; left: 80%;">
                <a style="background-color: #333333; color: white; padding: 10px; display: inline;" onclick={refresh}>
                    <lightning-icon class="slds-button__icon
                    slds-icon-utility-down slds-icon_container forceIcon" icon-name="utility:refresh" size="x-small">
                    </lightning-icon>
                </a>
                <span>&nbsp;</span>
                <a style="background-color: #333333; color: white; padding: 10px; display: inline;" onclick={handleDeleteClick}>
                    <lightning-icon class="slds-button__icon
                    slds-icon-utility-down slds-icon_container forceIcon" icon-name="utility:delete" size="x-small">
                    </lightning-icon>
                </a>
                <span>&nbsp;</span>
                <a style="background-color: #333333; color: white; padding: 10px; display: inline;" onclick={handleCreateClick}>
                    <lightning-icon class="slds-button__icon
                    slds-icon-utility-down slds-icon_container forceIcon" icon-name="utility:add" size="x-small">
                    </lightning-icon>
                </a>
            </lightning-layout-item>
        </lightning-layout>
    </div>
    <div style="height: 300px;">
        <lightning-datatable
                show-row-number-column
                max-row-selection="1"
                onrowselection={handelSelection}
                key-field="id"
                data={records}
                columns={columns}
                default-sort-direction={defaultSortDirection}
                sorted-direction={sortDirection}
                sorted-by={sortedBy}
                onsort={onHandleSort}
                onsave={handleSave}
                draft-values={draftValues}
                onrowaction={handleRowAction}>
        </lightning-datatable>
    </div>
    <c-related-list-record-delete
        show-delete-dilog={showDeleteDilog}
        record-id={deleteRecordId}
        object-label={objectLabel}
        ondeletesuccess={handleDeleteSuccess}
        ondeletecancel={handleDeleteCancel}>
    </c-related-list-record-delete>

    <c-related-list-record-edit
        show-edit-dilog={showEditDilog}
        record-id={editWrapper.id}
        record-name={editWrapper.name}
        object-api-name={objectApiName}
        onupdatesuccess={handleUpdateSuccess}
        oncloseedit={handleEditCancel}>
    </c-related-list-record-edit>
</template>

basicDatatable.js

代码语言:javascript
复制
import { LightningElement, wire, track } from 'lwc';
import getContactListView from '@salesforce/apex/MC_ContactListViewController.getContactListView';
import { loadStyle } from 'lightning/platformResourceLoader';
import COMMON_STATIC from '@salesforce/resourceUrl/common_sfdc_css';
import { refreshApex } from '@salesforce/apex';
import { deleteRecord, updateRecord } from 'lightning/uiRecordApi';
import PHONE_FIELD from '@salesforce/schema/Contact.Phone';
import ID_FIELD from '@salesforce/schema/Contact.Id';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

const actions = [
    { label: 'Edit', name: 'edit' },
    { label: 'Delete', name: 'delete' },
];
const columns = [
    //{ label: 'Name', fieldName: 'name', type: 'text', sortable: true },
    { label: 'Name', fieldName: 'idLink', type: 'url', sortable: true,
        typeAttributes: { label: { fieldName: 'name' }, target: '_self' }, initialWidth: 300 },
    { label: 'Email', fieldName: 'email', type: 'text', sortable: true },
    { label: 'Phone', fieldName: 'phone', type: 'text', sortable: true, editable: true },
    // { label: 'OwnerName', fieldName: 'ownerName', type: 'text', sortable: true },
    { label: 'Birthdate', fieldName: 'birthdate', type: 'date', sortable: true },
    {
        type: 'action',
        typeAttributes: { rowActions: actions },
    },
];

export default class BasicDatatable extends LightningElement {
    columns = columns;
    @track refreshFlag = false;
    @track wiredRecordList = [];
    @track records;
    @track recordLength;
    @track selectedRecord;

    renderedCallback() {
        Promise.all([
            loadStyle(this, COMMON_STATIC + '/mcCommon.css')
        ]);
    }
    // eslint-disable-next-line @lwc/lwc/no-async-await
    async connectedCallback() {
    }

    @wire(getContactListView, {refreshFlag : '$refreshFlag'})
    wireRecords(result) {
        console.log('>>>>>result>>'+JSON.stringify(result));
        this.refreshFlag = false;
        this.wiredRecordList = result;
        if (result.data) {
            this.records = result.data;
            this.recordLength = result.data.length;
        } else if (result.error) {
            // エラー
        }
    }
    // refresh
    refresh() {
        refreshApex(this.wiredRecordList);
    }

    handelSelection(event) {
        if (event.detail.selectedRows.length > 0) {
            this.selectedRecord = event.detail.selectedRows[0].id;
        }
    }
    // Delete Action
    handleDeleteClick() {
        deleteRecord(this.selectedRecord)
        .then(() => {
            refreshApex(this.wiredRecordList);
        })
        .catch(error => {
        })
    }

    // Insert Action
    handleCreateClick() {
        let __self = this;
        let openUrl = '/s/contactcreatedata';
        let target = '_blank';
        let w = 680;
        let h = 580;
        let newWindow = window.open(openUrl, target, 'width=' + w + ',height=' + h)
            let iv = window.setInterval(function () {
                if (newWindow.closed) {
                    refreshApex(__self.wiredRecordList);
                    clearInterval(iv);
                }
            }, 1000);
    }

    // Sort Action
    @track defaultSortDirection = 'asc';
    @track sortDirection = 'asc';
    @track sortedBy;
    onHandleSort(event) {
        const { fieldName: sortedBy, sortDirection } = event.detail;
        let fields = new Map();
        fields.set('idLink', 'name');
        let sortByField = '';
        if (fields.has(sortedBy) ) {
            sortByField = fields.get(sortedBy);
        } else {
            sortByField = sortedBy;
        }
        const cloneData = [...this.records];
        cloneData.sort(this.sortBy(sortByField, sortDirection === 'asc' ? 1 : -1));
        console.log('>>cloneData>>:'+cloneData);
        this.records = cloneData;
        this.sortDirection = sortDirection;
        this.sortedBy = sortedBy;
    }

    sortBy(field, reverse, primer) {
        const key = primer
            ? function (x) {
                return primer(x[field]);
            }
            : function (x) {
                return x[field];
            };

        return function (a, b) {
            a = key(a);
            b = key(b);
            return reverse * ((a > b) - (b > a));
        };
    }

    // InLine Edit
    @track draftValues = [];
    handleSave(event) {
        const fields = {};
        fields[ID_FIELD.fieldApiName] = event.detail.draftValues[0].id;
        fields[PHONE_FIELD.fieldApiName] = event.detail.draftValues[0].phone;
        const recordInput = {fields};
        updateRecord(recordInput)
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Contact updated',
                    variant: 'success'
                })
            );
            // Display fresh data in the datatable
            return refreshApex(this.wiredRecordList).then(() => {
                // Clear all draft values in the datatable
                this.draftValues = [];
            });
        }).catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error updating or reloading record',
                    message: error.body.message,
                    variant: 'error'
                })
            );
        });
    }

    // Row Action
    handleRowAction(event) {
        const actionName = event.detail.action.name;
        const row = event.detail.row;
        switch (actionName) {
            case 'delete':
                this.deleteRow(row);
                break;
            case 'edit':
                this.editRow(row);
                break;
            default:
        }
    }

    // Delete Action
    @track deleteRecordId;
    @track showDeleteDilog = false;
    @track objectLabel = '担当者';
    deleteRow(row) {
        const { id } = row;
        this.deleteRecordId = id;
        this.showDeleteDilog = true;
    }
    handleDeleteSuccess() {
        this.showDeleteDilog = false;
        refreshApex(this.wiredRecordList);
    }
    handleDeleteCancel() {
        this.showDeleteDilog = false;
    }

    // Edit Action
    @track editWrapper = {
        id: '',
        name: ''
    }
    @track showEditDilog = false;
    @track objectApiName = 'Contact';
    editRow(row) {
        this.editWrapper.id = row.id;
        this.editWrapper.name = row.name;
        this.showEditDilog = true;
    }

    handleUpdateSuccess() {
        this.showEditDilog = false;
        refreshApex(this.wiredRecordList);
    }

    handleEditCancel() {
        this.showEditDilog = false;
    }

}

4.效果展示

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.删除子画面
  • 2.编辑子画面
  • 3.主Lwc的html中调用子画面
  • 4.效果展示
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档