Salesforce How To Refresh Page Data in Lightning Web Component(三)

2022-05-03 12:51:37 浏览数 (1)

使用Lwc打开一个新的浏览器窗口,当关闭窗口时也可以进行刷新操作,如下,点击加号按钮,打开登录画面,当登录成功时刷新ListView列表。

Window open() 方法

用于打开一个新的浏览器窗口或查找一个已命名的窗口。

代码语言:javascript复制
window.open(URL,name,specs,replace)

具体登录事件操作如下,当登录成功,关闭子画面时,使用refreshApex()方法刷新画面

代码语言:javascript复制
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);
    }

1.登录画面做成

contactCreateData.html

代码语言:javascript复制
<template>
    <lightning-record-edit-form object-api-name={objectApiName} onsuccess={handleSuccess}>
        <header class="slds-modal__header">
            <h2 class="title slds-text-heading--medium slds-hyphenate">{tittle}</h2>
        </header>
        <lightning-messages> </lightning-messages>
        <lightning-input-field field-name="Name"> </lightning-input-field>
        <lightning-input-field field-name="Email"> </lightning-input-field>
        <lightning-input-field field-name="Phone"> </lightning-input-field>
        <lightning-input-field field-name="Birthdate"> </lightning-input-field>
        <footer class="slds-modal__footer">
            <lightning-button class="slds-m-top_small" label="Cancel" onclick={handleReset}></lightning-button>
            <lightning-button class="slds-m-top_small" label="Save" type="submit"></lightning-button>
        </footer>
    </lightning-record-edit-form>
</template>

contactCreateData.js

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

export default class ContactCreateData extends LightningElement {
    @api recordId;
    @track contactId;
    @track objectApiName = 'Contact';
    @track tittle;

    connectedCallback() {
        this.tittle = '新規作成';
    }
    handleSuccess(event) {
        this.contactId = event.detail.id;
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success!',
                message: 'Contact is Create Succeeded',
                variant: 'success'
            })
        );
        setTimeout(() => {
            window.close();
        }, 2000);
    }
    handleReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}

contactCreateData.js-meta.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightningCommunity__Default,lightning__RecordPage">
            <property name="recordId" type="String" label="Record ID" default="{!recordId}"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

2.Experiences上做一个新的Page,装载上边的登录画面。

3.ListView画面调用子画面(登录画面)

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="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}>
        </lightning-datatable>
    </div>
</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 } from 'lightning/uiRecordApi';
const columns = [
    { label: 'Name', fieldName: 'name', type: 'text' },
    { label: 'Email', fieldName: 'email', type: 'text' },
    { label: 'Phone', fieldName: 'phone', type: 'text' },
    { label: 'OwnerName', fieldName: 'ownerName', type: 'text' },
    { label: 'Birthdate', fieldName: 'birthdate', type: 'date' },
];

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;
        }
    }
    handleDeleteClick() {
        deleteRecord(this.selectedRecord)
        .then(() => {
            refreshApex(this.wiredRecordList);
        })
        .catch(error => {
        })
    }

    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);
    }
}

MC_ContactListViewController.cls

代码语言:javascript复制
public with sharing class MC_ContactListViewController {
    @AuraEnabled(cacheable=true)
    public static List<ContactWrapper> getContactListView(Boolean refreshFlag){
        List<ContactWrapper> wappers = new List<ContactWrapper>();
        List<Contact> resultList = [SELECT Id,Name,Email,Phone,Birthdate,Owner.Name
                        FROM Contact
                        LIMIT 100];

        if (resultList!=null && resultList.size() > 0) {
            for (Contact con : resultList) {
                ContactWrapper wapper = new ContactWrapper();
                wapper.id = con.Id;
                wapper.name = con.Name;
                wapper.email = con.Email;
                wapper.phone = con.Phone;
                wapper.ownerName = con.Owner.Name;
                wapper.birthdate = con.Birthdate;
                wappers.add(wapper);
            }
        }
        return wappers;
    }

    public class ContactWrapper {
        @AuraEnabled
        public String id;
        @AuraEnabled
        public String idLink;
        @AuraEnabled
        public String name;
        @AuraEnabled
        public String email;
        @AuraEnabled
        public String ownerName;
        @AuraEnabled
        public String phone;
        @AuraEnabled
        public Date birthdate;
    }
}

4.效果展示

0 人点赞