[SalesForce] onclick function on a lightning:datatable button

I'm using lightning:datatable as such:

 <aura:attribute name="resources" type="Object"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:handler name="init" value="{! this }" action="{! c.doInit }"/>
<lightning:datatable data="{! v.resources }"
                     columns="{! v.mycolumns }"
                     keyField="Id"
                     onrowaction="{! c.javascriptClickGoesHere}" // Is this what I need to do?
                     hideCheckboxColumn="true"
                     />

where I have set a button for each row:

{type: "button", typeAttributes: {
iconName: 'utility:add',
label: '',
name: 'selectRecord',
title: 'selectTitle',
disabled: false,
value: 'test',

I need to somehow use an onclick on each button (as I'm interested in getting the record ID for the button on the row clicked)

With regular lightning:button, I'd have something like onclick="{!c.onClick}" and in the controller

onClick: function(component, event, helper) {
    var resource = component.get("v.resource");
    var event = component.getEvent("ResourceSelected");

    event.setParams({
        resourceId: resource.Id, 
    });
    event.fire();
},

How can I achieve the same effect with the button in datatables? onrowaction?

Best Answer

This is an example with LWC lightning-datatable using button as a column and retriving the information with onrowaction, but, the same should be applied to Aura Component lightning:datatable

onrowaction will return the action trigger in the row, it means, from An action field type, from a button or button-icon.

Javascript event:

  • event.detail.action.name => Returns the value of the name set in typeAttributes.
  • event.detail.row => Returns an Object with the values of the row
  • event.detail.row.columnFieldName => Returns the value in an specific column

Paste this example in LWC Playground and check out the Console:

HTML

<template>
    <div style="height: 300px;">
        <lightning-datatable
                key-field="id"
                data={data}
                columns={columns}
                onrowaction={viewRecord}/>>
        </lightning-datatable>
    </div>    
</template>

Basic.js

import { LightningElement } from 'lwc';
import fetchDataHelper from './fetchDataHelper';

const columns = [
    { label: 'Label', fieldName: 'name' },
    { label: 'Website', fieldName: 'website', type: 'url' },
    { label: 'Phone', fieldName: 'phone', type: 'phone' },
    { label: 'Balance', fieldName: 'amount', type: 'button',
        typeAttributes: {
            label: { fieldName: 'amount' },
            name: 'amount'
        },
    },
    { label: 'CloseAt', fieldName: 'closeAt', type: 'date' },
];

export default class BasicDatatable extends LightningElement {
    data = [];
    columns = columns;

    viewRecord(event){
        console.log(event.detail.action.name);
        console.log(event.detail.row.name);
    }

    // eslint-disable-next-line @lwc/lwc/no-async-await
    async connectedCallback() {
        const data = await fetchDataHelper({ amountOfRecords: 100 });
        this.data = data;
    }
}

fetchDataHelper.js

const recordMetadata = {
    name: 'name',
    email: 'email',
    website: 'url',
    amount: 'currency',
    phone: 'phoneNumber',
    closeAt: 'dateInFuture',
};

export default function fetchDataHelper({ amountOfRecords }) {
    return fetch('https://data-faker.herokuapp.com/collection', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
        },
        body: JSON.stringify({
            amountOfRecords,
            recordMetadata,
        }),
    }).then(response => response.json());
}
Related Topic