Lightning Web コンポーネントを作成するサンプル

環境
salesforce

1.parent.js
Lightning データサービスを使用して取引先オブジェクトを照会します。
サンプルコード

import { LightningElement, api, wire } from "lwc";
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import FIELD_NAME from "@salesforce/schema/Account.Name";
import FIELD_OWNER_NAME from "@salesforce/schema/Account.Owner.Name";
import FIELD_PHONE from "@salesforce/schema/Account.Phone";
import FIELD_INDUSTRY from "@salesforce/schema/Account.Industry";
export default class Parent extends LightningElement {
      @api recordId;
      @wire(getRecord, { recordId: "$recordId", fields: [FIELD_NAME, FIELD_INDUSTRY], optionalFields: [FIELD_PHONE, FIELD_OWNER_NAME] })
account;
      get name() {
            return getFieldValue(this.account.data, FIELD_NAME);
}
      get phone() {
            return getFieldValue(this.account.data, FIELD_PHONE);
}
      get industry() {
            return getFieldValue(this.account.data, FIELD_INDUSTRY);
}
      get owner() {
            return getFieldValue(this.account.data, FIELD_OWNER_NAME);
}
      sayHi() {
            let cmp = this.template.querySelector("c-child");
            cmp.sayHi();
     }
}

2.parent.js-meta.xml
取引先のレコード詳細ページでこのコンポーネントを使用可能になります。

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>58.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Account</object>
            </objects>
        </targetConfig>
   </targetConfigs>
</LightningComponentBundle>

3.parent.html
条件に応じて取引先情報かエラーのいずれかを表示します。

<template>
      <lightning-card title="Summer '23 Maintenance">
            <lightning-button slot="actions" label="Say Hi" onclick={sayHi}></lightning-button>
            <template if:true={account.data}>
                  <div class="slds-m-around_medium">
                        <p>Account Name: {name}</p>
                        <p>Industry: {industry}</p>
                        <p>Phone: {phone}</p>
                        <p>Owner: {owner}</p>
                 </div>
           </template>
           <template if:false={account.data}>
                <div class="slds-m-around_medium slds-text-color_destructive">An error occurred while retrieving data</div>
           </template>
           <c-child></c-child>
     </lightning-card>
</template>

 

IT

Posted by arkgame