Sample Code:
Component:
Component:
- <aura:component implements = “force:appHostable”
- controller = “AccountListController”>
- <aura:attribute type = “object[]” name = “acctList”/>
- <aura:attribute name = “mycolumns” type = “List”/>
- <aura:handler name = “init” value=“{!this}” action=“{!c.onInit}”/>
- <lightning:datatable aura:id = “acctTable”
- data = “{! v.acctList }”
- columns = “{! v.mycolumns }”
- keyField = “Id”
- hideCheckboxColumn = “true”
- onrowaction = “{! c.viewRecord }”/>
- </aura:component>
Controller:
- ({
- onInit : function( component, event, helper ) {
- component.set( ‘v.mycolumns’, [
- {label: ‘Account Name’, fieldName: ‘Name’, type: ‘text’, editable:‘true’},
- {label: ‘Industry’, fieldName: ‘Industry’, type: ‘text’},
- {label: ‘Type’, fieldName: ‘Type’, type: ‘Text’},
- {type: “button”, typeAttributes: {
- label: ‘View’,
- name: ‘View’,
- title: ‘View’,
- disabled: false,
- value: ‘view’,
- iconPosition: ‘left’,
- variant: { fieldName: ‘buttonColor’}
- }}
- ]);
- helper.fetchAccounts( component );
- },
- viewRecord : function( component, event, helper ) {
- var recId = event.getParam( ‘row’ ).Id;
- var actionName = event.getParam( ‘action’ ).name;
- var viewRecordEvent = $A.get( “e.force:navigateToURL” );
- viewRecordEvent.setParams({
- “url”: “/” + recId
- });
- viewRecordEvent.fire();
- }
- })
Helper:
- ({
- fetchAccounts : function( component ) {
- var action = component.get( “c.fetchAccts” );
- action.setCallback(this, function( response ) {
- var state = response.getState();
- if ( state === “SUCCESS” ) {
- var records = response.getReturnValue();
- for ( var i = 0; i < records.length; i++ ) {
- if ( records[ i ].Industry === “Energy” )
- records[ i ].buttonColor = ‘white’;
- else if ( records[ i ].Industry === “Electronics” )
- records[ i ].buttonColor = ‘brand’;
- else if ( records[ i ].Industry === “Biotechnology” )
- records[ i ].buttonColor = ‘destructive’;
- else if ( records[ i ].Industry === “Construction” )
- records[ i ].buttonColor = ‘success’;
- else
- records[ i ].buttonColor = ‘neutral’;
- }
- component.set( “v.acctList”, records );
- }
- });
- $A.enqueueAction(action);
- }
- })
Apex Class:
- public class AccountListController {
- @AuraEnabled
- public static List < Account > fetchAccts() {
- return [ SELECT Id, Name, Industry, Type, CreatedDate FROM Account LIMIT 100 ];
- }
- }
Output: