import { LightningElement, api, wire } from 'lwc'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import { invoke } from '@salesforce/apex/MyController.callLightningAction'; // Apex メソッドの呼び出し export default class MyLWC extends LightningElement { // コンポーネントの初期化処理などを追加する場合はここに記述 callLightningAction() { // Apex メソッドを呼び出して Lightning アクションを実行 invoke({ actionName: 'Your_Lightning_Action_Name' }) .then(result => { // アクションが成功した場合の処理 this.showToast('Success', 'Lightning Action was called successfully.', 'success'); }) .catch(error => { // アクションが失敗した場合の処理 this.showToast('Error', 'An error occurred while calling Lightning Action: ' + error.body.message, 'error'); }); } showToast(title, message, variant) { const event = new ShowToastEvent({ title: title, message: message, variant: variant, }); this.dispatchEvent(event); } }
Apex メソッド(MyController.cls): apex Copy code
public with sharing class MyController { @AuraEnabled(cacheable=true) public static String callLightningAction(String actionName) { // Lightning アクションを呼び出すロジックを実装 // 成功または失敗時の結果を返す // 例: 何らかの処理を実行し、成功した場合は結果を返す try { // 何らかの処理 return 'Success'; } catch (Exception e) { // エラー時の処理 return 'Error: ' + e.getMessage(); } } }
Lightning アクションの設定: Salesforceの設定で Lightning アクションを作成し、そのアクション名(Your_Lightning_Action_Name)を Lightning Web コンポーネントの JavaScriptコードで指定します。 このサンプルコードを使用すると、Lightning Web コンポーネント内に表示されるボタンをクリックすると指定した Lightning アクションが呼び出され、アクションの実行結果に応じてメッセージが表示されます。
public PageReference callLightningAction() { PageReference action = Page.Your_Lightning_Action_Name; // Lightningアクションの名前を指定 action.getParameters().put('param1', 'value1'); // アクションに渡すパラメータを設定 action.getParameters().put('param2', 'value2'); return action; }
// navigateToAction.js import { LightningElement } from 'lwc'; import { NavigationMixin } from 'lightning/navigation'; export default class NavigateToAction extends NavigationMixin(LightningElement) { navigateToAction() { // Lightning アクションへの遷移設定を作成 const actionName = 'standard__recordPage'; // レコードページへの遷移 const attributes = { recordId: 'レコードのID', // 遷移先レコードのIDを指定 objectApiName: 'オブジェクトのAPI名', // 遷移先オブジェクトのAPI名を指定 actionName: 'アクションの名前' // 遷移先の Lightning アクションの名前を指定 }; // 遷移を実行 this[NavigationMixin.Navigate]({ type: actionName, attributes }); } }