1
0

Lightning Web Componentsでのトースト表示

Posted at

前提とやりたいこと

・取引先(Account)を参照する調査結果(SurveyResult__c)オブジェクトがあるとする
・取引先の詳細画面を開いたときに、LWCを利用し関連する調査結果レコードで最終更新日が最も新しいレコードを取得する
・取得したレコードの最終更新日と現在の日付の差分を取り、任意の日数経過していた場合にトーストメッセージを出力する

取引先に調査結果を紐づけて管理していて、一定日数調査されていないと注意が表示される。なんていう場面を仮に設定しています

イメージ

取引先の詳細画面を開いたら注意書きをトースト表示するようにします
image.png

実装内容

「accountChildInfoWarn」という名称でLWCを作成しました
各ファイルの実装内容は以下の通りです

accountChildInfoWarn.js
import { LightningElement, api, wire, track } from 'lwc';
import getSurveyResultLatestLastmodifiedData from '@salesforce/apex/AccountSurveyResultController.getSurveyResultLatestLastmodifiedData';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const TARGET_NUMBER_OF_DAYS = 2;

export default class AccountChildInfoWarn extends LightningElement {
    @api recordId;

    @wire(getSurveyResultLatestLastmodifiedData, { testStr: '$recordId' })
    getTableData({ error, data }) {
        if (data) {
            data.forEach(element => {
                // 今日の日付情報
                var now = new Date();
                // 取得したSurveyResult__cの日付情報
                var lastMdDate = new Date(element.LastModifiedDate);
                // 差分の計算
                var dateDiff = this.calcDateDifference(now, lastMdDate);
                // 基準の日数以上経過していたら、TOAST表示する
                if(TARGET_NUMBER_OF_DAYS <= dateDiff){
                    console.log('test output');
                    console.log(element.Id);
                    this.showErrorToast('注意!', '最後の調査から2日間以上経過しています');
                }
            });
            
        }else if(error){
            console.log('Something happened: ' + JSON.parse(JSON.stringify(error)));
        }
    }

    showErrorToast(title, message) {
        const evt = new ShowToastEvent({
            title: title,
            message: message,
            variant: 'error',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    calcDateDifference(dateNow, lastModofiedDayte) {
        // 今日の日付と取得したSurveyResult__cの最終更新日を比較できるように変換
        var today = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate());
        var elementDay = new Date(lastModofiedDayte.getFullYear(), lastModofiedDayte.getMonth(), lastModofiedDayte.getDate());
        // 日数の差を計算
        var termDay = (today - elementDay) / 86400000;
        return termDay;
    }
}

const TARGET_NUMBER_OF_DAYS = 2;
で基準となる日数を定義しています。ここでは2日間としてみました

@wireを使って、Apexを呼び出しています
返ってきたレコードの最終更新日と現在の日付の差分をとって、2日間以上経過していたらトースト表示するようにしています

上記のJavascriptから呼び出しているApexは以下の通りです

AccountSurveyResultController.cls
public with sharing class AccountSurveyResultController {
    @AuraEnabled(cacheable=true)
    public static List<SurveyResult__c> getSurveyResultLatestLastmodifiedData(Id testStr) {
        List<SurveyResult__c> srlst = [
            SELECT Id, Name, Account__c, LastModifiedDate
            FROM SurveyResult__c
            WHERE Account__c = :testStr
            ORDER BY LastModifiedDate DESC LIMIT 1
       ];
       return srlst;
    }
}

本当は権限チェックとかしないといけないと思いますが、省略します

HTMLでの画面出力はないので「accountChildInfoWarn.html」はいじってません

感想

今まではこのような注意書きはフローを用いていたので、幅が広がった気がします
入力規則を使うほどの制限はかけたくないけど、注意して修正してほしいとか、参照関係だけど積み上げ集計で使用できる項目も使いたいみたいな時に応用できると思いました

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0