【问题标题】:How to refresh datatable content after insert operation in modal window using LWC如何使用LWC在模态窗口中插入操作后刷新数据表内容
【发布时间】:2022-11-24 06:05:46
【问题描述】:

当从组合框中选择来自客户对象的特定记录时,我有一个 LWC 组件显示一个显示相关联系人的数据表。还会显示一个按钮,单击该按钮会调用一个模式窗口,允许将记录添加到所选帐户的联系人对象。 我的要求是,通过模态窗口插入记录后,数据表中的列表也应该刷新。 我无法在这里正确使用@wire 装饰器。 任何帮助表示赞赏。 代码贴在下面:

accountContactsdatatable.html

<template>
    <lightning-card title="Select Account">
        <!--Combobox to select Account-->
        <lightning-combobox label="Accounts"
                            value={value}
                            placeholder = "Select an Account"
                            options={options}
                            onchange={handleChangedValue}
        ></lightning-combobox>                        
    </lightning-card>

    <template if:true={addButton}>
        <div class='slds-card'>
            <!--Add contact button-->
            <lightning-button label='Add Contact'
                              titlle='Add Contact'
                              onclick={addContact}>
            </lightning-button>
        </div>
    </template>
           
    <!-- Modal window -->        
    <template if:true={modalWindow}>
        <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">
                    <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={customHideModalPopup}>
                        <lightning-icon icon-name="utility:close"
                                        alternative-text="close"
                                        variant="inverse"
                                        size="small" >
                        </lightning-icon>
                        <span class="slds-assistive-text">Close</span>
                    </button>
                    <h2 class="slds-text-heading_medium slds-hyphenate">Enter Contact Details</h2>
                </header>
                <div class="slds-modal__content slds-p-around_medium">
                    <div class="slds-grid slds-wrap">
                        <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom_medium">
                            <lightning-input label="First Name" value={rec.FisrtName} onchange={fnameChange}></lightning-input>
                        </div>
                        <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom_medium">
                            <lightning-input label="Last Name" value={rec.LastName} onchange={lnameChange}></lightning-input>
                        </div>
                        <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom_medium">
                            <lightning-input label="Email" value={rec.Email} onchange={emailChange}></lightning-input>
                        </div>
                        <div class="slds-col slds-size_6-of-12 slds-p-horizontal--medium slds-m-bottom_medium">
                            <lightning-input label="Mobile" value={rec.Mobile} onchange={mobileChange}></lightning-input>
                        </div>
                        <footer class="slds-modal__footer">
                            <button class="slds-button slds-button--destructive" onclick={customHideModalPopup}>Cancel</button>
                            <button class="slds-button slds-button_brand" onclick={createContact}>Create Contact</button>
                        </footer>
                    </div>
                </div>
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open">
        </div>
    </template>
    <!--Datatable-->
    <template if:true={dataTable}>
        <lightning-card title="Contacts">
            <div style="height: 200px">
                <lightning-datatable key-field="id"
                                     data={data}
                                     columns={columns}>
                </lightning-datatable>
            </div>
        </lightning-card>
    </template> 
</template>

accountContactsdatatable.js

import { LightningElement, track, wire } from 'lwc';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import FNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LNAME_FIELD from '@salesforce/schema/Contact.LastName';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import MOBILE_FIELD from '@salesforce/schema/Contact.MobilePhone';
import ACID_FIELD from '@salesforce/schema/Contact.AccountId';
import getAccounts from '@salesforce/apex/accountsContactdatatableController.getAccounts';
import getContacts from '@salesforce/apex/accountsContactdatatableController.getContacts';
import insertContact from '@salesforce/apex/accountsContactdatatableController.insertContact';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

const columns = [
    {label : 'Contact Name', fieldName : 'Name'}
]

export default class AccountContactsdatatable extends LightningElement {

    @track value = '';
    refreshTable;
    @track optionList = [];
    @track data = [];
    @track columns = columns;
    @track modalWindow = false;
    @track dataTable = false;
    @track addButton = false;
    @track fname = FNAME_FIELD;
    @track lname = LNAME_FIELD;
    @track email = EMAIL_FIELD;
    @track mobile = MOBILE_FIELD;
    @track actid = ACID_FIELD;
    rec = {
        FirstName : this.fname,
        LastName : this.lname,
        Email : this.email,
        Mobile : this.mobile,
        AccountId : this.value
    }

    get options(){
        return this.optionList;
    }

    connectedCallback(){
        getAccounts()
        .then(response=>{
            let arr = [];
            for(var i=0; i<response.length; i++){
                arr.push({label : response[i].Name, value : response[i].Id});
            }
            this.optionList = arr;
        })   
    }

    handleChangedValue(event){
        this.value = event.detail.value;
        this.addButton = true;
        this.dataTable = true;

        getContacts({AcctId : this.value})
        .then(result=>{
            this.data = result;
            this.refreshTable = result;
        })
        .catch(error =>{
            window.alert("Error:"+error)
        })
    }

    addContact(){
        this.modalWindow = true;
    }

    customHideModalPopup(){
        this.modalWindow = false;
    }

    createContact(event){
        this.rec.AccountId = this.value;
        insertContact({ cnt : this.rec })
        .then(result => {
            this.message = result;
            this.error = undefined;
            if(this.message !== undefined) {
                this.rec.FirstName = '';
                this.rec.LastName = '';
                this.rec.Email = '';
                this.rec.Mobile = '';
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created Succesfully',
                        variant: 'success',
                    }),
                );
            }
        })
        .catch(error => {
            this.message = undefined;
            this.error = error;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Failed to create contact',
                    message: error.body.message,
                    variant: 'error',
                }),
            );
        });

        this.customHideModalPopup();
    }

    fnameChange(event){
        this.rec.FirstName = event.target.value;
    }

    lnameChange(event){
        this.rec.LastName = event.target.value;
    }

    emailChange(event){
        this.rec.Email = event.target.value;
    }

    mobileChange(event){
        this.rec.Mobile = event.target.value;
    }
}

accountsContactdatatableController.cls

public with sharing class accountsContactdatatableController {
    //Method to return list o Accounts to LWC
    @AuraEnabled
    public static List<Account> getAccounts(){
        try {
            List<Account> accountList = [SELECT Id, Name FROM Account];
            return accountList;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

    //Method to return related contacts to LWC
    @AuraEnabled
    public static List<Contact> getContacts(String AcctId){
        try {
                List<Contact> cntcList = [SELECT Id,Name,AccountId FROM Contact WHERE AccountId =: AcctId];
                return cntcList;
            } catch (Exception e) {
                throw new AuraHandledException(e.getMessage());
            }
    }

    //Method to insert record in Contact object
    @AuraEnabled
    public static Contact insertContact(Contact cnt){
        try {
                insert cnt;
                return cnt;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

TIA。

【问题讨论】:

    标签: datatables salesforce apex lwc


    【解决方案1】:

    您为此需要顶点代码有什么特殊原因吗?查看(相对较新的)https://developer.salesforce.com/docs/component-library/bundle/lightning-ui-related-list-api/documentation,也许您可​​以使用纯 LWC 将其全部完成。

    刷新数据表...嗯。

    您可以尝试显式调用的马马虎虎的方式

    getContacts({AcctId : this.value})
            .then(result=>{
                this.data = result;
                this.refreshTable = result;
            })
            .catch(error =>{
                window.alert("Error:"+error)
            })
    

    在您的联系人中插入成功。它应该可以工作,因为您没有将 Apex 方法标记为可缓存。

    更好的方法 - 是的,顶点方法应该是 @AuraEnabled(cacheable=true) 以获得更好的性能。然后这个技巧就不起作用了,因为 SF 会看到相同的帐户 ID 已通过,并且会决定无事可做。在 JS 中有一个 refreshApex 调用将强制 lwc 再次调用该方法并获取新数据。

    或者您可以将插入的联系人添加到 JS 列表中,我的意思是您将它从顶点返回到 JS ...

    或者放弃整个事情并检查相关记录 API。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      相关资源
      最近更新 更多