Salesforce LWC学习(四十七) 标准页面更新以后自定义页面如何捕捉?

发布时间 2023-12-26 11:11:13作者: zero.zhang

本篇参考: 

https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_subscribe_lc.htm

https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation

salesforce零基础学习(九十六)Platform Event浅谈

Salesforce LWC学习(五) LDS & Wire Service 实现和后台数据交互 & meta xml配置

 

背景: 我们在记录的详情页面,除标准的layout以外,实际工作中也会添加各种各样的component来满足实际业务的需要,有一些是标准组件,有一些是自定义组件。自定义组件间的修改和交互很好弄,我们可以通过 notifyRecordUpdateAvailable搞定(Lighting Data Service)LDS的缓存问题,通过 refreshApex搞定 call apex方法的问题,通过 dispatchEvent / handler方式来搞定父子组件通信的事情,通过pub / sub事件模型来搞定跨组件通讯问题,通过 lightning message service或者 dynamic interaction也可以搞定跨组件通讯问题。如上的内容都是自定义组件之间或者自定义组件的行为渲染到标准组件。那我们如何针对标准组件的更新作用到自定义页面,然后自定义页面捕捉到这些事件操作呢? 本篇提供两种思路。

需求: 当用户在Account详情页面更新数据时,不管使用 quick action的Edit还是 Inline Edit,当Account的Name包含Test的字样,显示一个toast信息。

一. 基于Lightning Data Service(LDS)

这个demo可以基于getRecord的这个wire adapter来实现。因为 getRecord以及标准UI都共用同一个version的数据,所以当标准UI因为用户修改以后,我们通过 getRecord也同样可以自动收到最新的version的数据,所以我们可以基于 getRecord的这个wire adapter来实现。

import { LightningElement, api, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from "@salesforce/schema/Account.Name";
export default class toastDemo extends LightningElement {

    @api recordId;

    @wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD]})
    // eslint-disable-next-line no-unused-vars
    wiredAccount(data, error) {
      if (data.data && data.data.fields && data.data.fields.Name) {
          if(data.data.fields.Name.value.includes('test')) {
              this.showToast();
          }
      } else if(error) {
          console.log('error');
      }
    }


    showToast() {
        const evt = new ShowToastEvent({
            message: 'Name contains test',
            variant: 'info',
        });
        this.dispatchEvent(evt);
    }
}

效果演示:将这个组件放在 lightning record page中

 二. 基于Platform Event 订阅实现

 如果对Platform Event不了解的,欢迎查看以前的博客内容。思路为当Account Name变动以后,发布一个Account的Platform Event,lwc端用来订阅这个Platform Event,对订阅的结果进行解析,如果满足了预期,则进行逻辑处理。

1. 创建Platform Event的表以及字段。

 2. 通过Flow或者Trigger,Account Name包含test情况下,发布Platform Event.

 3. lwc进行订阅:这里看一下加粗的两行,messageCallback函数看上去有自己的上下文,如果不传递进去,获取的recordId则为 undefined, context也相同。

import { LightningElement, api, wire } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from "lightning/empApi";
export default class toastDemo extends LightningElement {
  channelName = "/event/Account_Change__e";

  @api recordId;

  get changedRecordId() {
    return this.targetedRecordId;
  }

  subscription = {};

  // Initializes the component
  connectedCallback() {
    // Register error listener
    this.registerErrorListener();
    const currentRecordId = this.recordId;
    const context = this;
    const messageCallback = function (response) {
      // Response contains the payload of the new message received
      let event = response.data.payload;

      if (event.Account_Id__c == currentRecordId) {
        const evt = new ShowToastEvent({
          message: "Name contains test",
          variant: "info"
        });
        context.dispatchEvent(evt);
      }
    };

    // Invoke subscribe method of empApi. Pass reference to messageCallback
    subscribe(this.channelName, -1, messageCallback).then((response) => {
      // Response contains the subscription information on subscribe call
      console.log("Subscription request sent to: ", JSON.stringify(response.channel));
      this.subscription = response;
    });
  }

  disconnectedCallback() {
    unsubscribe(this.subscription, (unsubResp) => {
      console.log("unsubscribe() response: ", JSON.stringify(unsubResp));
    });
  }

  registerErrorListener() {
    // Invoke onError empApi method
    onError((error) => {
      console.log("Received error from server: ", JSON.stringify(error));
      // Error contains the server-side error
    });
  }
}

效果:

 总结:本篇主要介绍的是标准页面编辑数据情况下自定义的lwc页面如何进行捕捉然后做一些逻辑,其中LDS方式固然好用,但是没有那么灵活,如果需求简单,推荐使用LDS方式,否则可以考虑订阅Platform Event来实现。篇中有错误地方欢迎指出,有不懂欢迎留言。