LoginSignup
2
4

More than 1 year has passed since last update.

【LWC】datatableでrowActionを使用する

Posted at

はじめに

今回はdatatableのrowActionについて書きます。rowActionとは標準のリストビューの「編集、削除、所有者の変更」の3つのアクションが表示されるメニューのことです。datatableではカスタムで様々なアクションを作成することが出来ます。

actionを定義

まずrowActionとして表示するactionを定義します。今回は詳細画面へのリンクと削除です。

const actions = [
  {label: 'Details', name: 'details'},
  {label: 'Delete', name: 'delete'},
];

datatableのcolumnsにtype='actionを追加

定義したアクションを他のカラムと同様にcolumnsに定義します。

const columns = [
    { label: '商談名', fieldName: 'Name'},
    { label: '金額', fieldName: 'Amount', type: 'currency'},
    { label: 'フェーズ', fieldName: 'StageName', type: 'text', editable: true},
    // 定義したAction
    { type: 'action', typeAttributes: {rowActions: actions, menuAlignment: 'right'}},
];

HTMLにonrowaction属性を追加

actionの定義が出来たらhtml側にonrowaction属性を追加します。

opportunityTable
<template>
    <div>
        <lightning-datatable
            key-field="id"
            data={records}
            columns={columns}
            hide-checkbox-column="true"
            show-row-number-column="true"
            onrowaction={handleRowAction}>
        </lightning-datatable>
    </div>
</template> 

あとは個々のactionに対する処理を書いていけば完成です。今回は詳細ページへの遷移しか処理を書いてませんが、参考までに載せておきます。

opprotunityTable.js
import { LightningElement, wire, api } from 'lwc';
import getOppTable from '@salesforce/apex/OpportunityTableController.getOppTable';
import { NavigationMixin } from 'lightning/navigation';

const actions = [
  {label: 'Details', name: 'details'},
  {label: 'Delete', name: 'delete'},
];

const columns = [
    { label: '商談名', fieldName: 'Name'},
    { label: '金額', fieldName: 'Amount', type: 'currency'},
    { label: 'フェーズ', fieldName: 'StageName', type: 'text', editable: true},
    { type: 'action', typeAttributes: {rowActions: actions, menuAlignment: 'right'}},
];

export default class OpportunityTable extends NavigationMixin(LightningElement) {

  columns = columns;
  records;
  @api recordId;

  @wire(getOppTable, {accId: '$recordId'})
  wiredOpps({error, data}) {
    if(data) {
      this.records = data;
    }
  }

  handleRowAction(event) {
    console.log('' + event.detail.action.name);
    let actionName = event.detail.action.name;
    let row = event.detail.row;
    switch(actionName) {
      case 'details':
        // navigate to record detail page
        this[NavigationMixin.Navigate]({
          type: 'standard__recordPage',
          attributes: {
            recordId: row.Id,
            actionName: 'view'
          }
        });
        break;
      case 'delete':
        alert('delete but not really');
        break;
    }
  }
}

標準では出来ないようなアクションも定義できると思うので使い道は多いのではないでしょうか。

2
4
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
2
4