add icon and style LC

Conditionally Add Icon And Style On Records In Salesforce Lightning DataTable Component

Lightning Component

Scenario – When an account record is marked as important(the custom field checkbox VIP_Account__c is enabled) in the account record detail page, an slds-icon “check” appears in the lightning datatable and the record will be highlighted in red color.
When an account record is marked as not important(the custom field checkbox VIP_Account__c is disabled) in the account record detail page, an slds-icon “close” appears in the lightning datatable and the record will be highlighted in black color.

Prerequisites- Create a custom field in account of type checkbox and give the name – VIP_Account__c.

 

lightning datatable with icon

From developer console >> file >> new >> apex class

Apex Controller : AccountDataTable.apxc
/*
 Source : sfdcMonkey.com
 Date : 3/13/2019
 API : 45.00
*/
public class AccountDataTable {
    /*apex method to fetch account list*/
    @AuraEnabled
    public static List <Account> getAccounts() {
        List<Account> accountList = new List<Account>();
        for(Account Acc : [SELECT  Name, Industry, Type, VIP_Account__c FROM Account ORDER BY LastModifiedDate DESC LIMIT 20]){
            accountList.add(Acc);
        }
        return accountList;
    }
}

From developer console >> file >> new >> Lightning Component 

Lightning Component : datatableWithIcon.cmp
<!--
  Source : sfdcMonkey.com
  API : 45.00
  Date : 3/13/2019
-->
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"
                access="global"
                controller="AccountDataTable" >
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccountDetails}"/>
    
    <aura:attribute type="account[]" name="accountList"/>
    <aura:attribute name="tableCol" type="List"/>
    
    <lightning:datatable data="{! v.accountList }" 
                         columns="{! v.tableCol }"
                         keyField="id"
                         hideCheckboxColumn="true"/>
</aura:component>
JavaScript Controller : datatableWithIconController.js
/*
  Source : sfdcMonkey.com
  API : 45.00
  Date : 3/13/2019
*/
({
    fetchAccountDetails : function(component, event, helper) {
        // set table columns in variable
        var tableColumns = [
            {
                "label": "Important Account",
                "fieldName": "VIP_Account__c",
                "cellAttributes": {
                    "class": {
                        "fieldName": "showClass"
                    },
                    "iconName": {
                        "fieldName": "displayIconName"
                    }
                }
            },
            {
                "label": "Account Name",
                "fieldName": "linkName",
                "type": "url",
                "typeAttributes": {
                    "label": {
                        "fieldName": "Name"
                    },
                    "target": "_blank"
                },
                "cellAttributes": {
                    "class": {
                        "fieldName": "showClass"
                    }
                }
            },
            {
                "label": "Industry",
                "fieldName": "Industry",
                "type": "picklist",
                "cellAttributes": {
                    "class": {
                        "fieldName": "showClass"
                    }
                }
            },
            {
                "label": "Account Type",
                "fieldName": "Type",
                "type": "picklist",
                "cellAttributes": {
                    "class": {
                        "fieldName": "showClass"
                    }
                }
            }
        ];
        // set tableCol attribute with table columns
        component.set('v.tableCol', tableColumns);
        
        // call server side apex method to fetch account records
        var action = component.get("c.getAccounts");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                // store the account list in records variable
                var records = response.getReturnValue();
                // iterate each records with forEach loop
                records.forEach(function(record){ 
                    if(typeof record.Id != 'undefined'){ 
                        // based on VIP Account field value set the icon and style class to each record 
                        // https://www.lightningdesignsystem.com/icons/#utility 
                        if(record.VIP_Account__c){
                            record.showClass = (record.VIP_Account__c === true ? 'redcolor' : 'blackcolor');
                            record.displayIconName = 'utility:check';  
                        }
                        else{
                            record.showClass = (record.VIP_Account__c === false ? 'blackcolor' : 'redcolor');
                            record.displayIconName = 'utility:close';     
                        }
                        // set the record link with record id  
                        record.linkName = '/'+record.Id;   
                    }
                });
                // after the loop set the updated account records on "accountList" aura attribute
                component.set("v.accountList", records);
            }
        });
        $A.enqueueAction(action);
    }
})
  • Check code comments.

3 Ways to Use CSS In Lightning Component.

CSS : datatableWithIcon.css
.THIS .redcolor svg{
    fill : red;
}
.THIS .redcolor, .THIS .redcolor a{
    color: red ;
}
.THIS .redcolor svg{
    fill: red !important;
}
.THIS .blackcolor svg{
    fill : black; 
}
.THIS .blackcolor{
    color : black ;
}
.THIS .blackcolor a{
    color : black ;
}
.THIS .blackcolor svg{
    color : black !important;
}
TestApp :

From developer console >> file >> new >> Lightning Application

<aura:application extends="force:slds">
    <c:datatableWithIcon/>
<!-- here c: is org. default namespace prefix--></span>
</aura:application>

check code comments.

Output :

add icon to lightning datatable salesforce

Related Resources :

Other popular Post :

Like our facebook page for new post updates. & Don’t forget to bookmark this site for your future reference.

if you have any suggestions or issue with it, you can post in comment box.

Happy Learning ?

About The contributor: 

Shovan Mandal

1 Post Contribute
shovan sfdcMonkey
Working with Infosys from last 3 years. Mentored 500+ people in Salesforce. Volunteer for the Hyderabad Trailblazin 2018 and anchored for three events.
Active volunteer/member for the Hyderabad SFDC developer group for the last 1 and half year.
My Hobbies- Exploring different places, A great foodie, Reading Books.
My Favorite Quote- Arise awake and stop not till the goal is reached.
Post By Shovan :

2 comments

  • Styling inside init method is working perfectly but I have a scenario where account data is provided by another component in attribute. Data gets updated in the data table but styling does not apply since component is not rendered and init method is not invoked. Any idea how styling code can be re-run whenever account data inside attribute is changing.

Leave a Reply