Requirement:
While working on one of the user stories of healthcare sector project for a client based out of Atlanta, GA, USA, there was a need of displaying a list of Contacts in lightning:datatable having 2 columns with hyperlinks. One is contact name and other is account name. And clicking on it, it should redirect to contact record and account record respectively.Challenge:
The challenging part was, there is no standard functionality available in the lightning:datatable for a hyperlink field to redirect to record detail page.Solution:
To overcome this limitation, we'd to make changes in column format for a Contact name and Account name fields with type:'url' and also need to add typeAttributes as display below.
{ label: 'Name', fieldName: 'contacturl', type: 'url', typeAttributes: { label: { fieldName: 'Name' }, target: '_blank' } }, { label: 'Account Name', fieldName: 'accounturl', type: 'url', typeAttributes: { label: { fieldName: 'AccountName' }, target: '_blank' } }
ContactController
public class ContactController { @AuraEnabled public static List < Contact > fetchContacts() { return [ SELECT Id, Name, Account.Id, Account.Name,Phone,Department,LeadSource FROM Contact]; } }
The contact controller class is referenced by the HyperLinkDatable component to display retrieved contacts as a data table.
HyperLinkDatable.cmp
<aura:component implements="force:appHostable" controller="ContactController"> <aura:attribute type="Contact[]" name="conList"/> <aura:attribute name="columns" type="List"/> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <lightning:datatable data="{!v.conList}" columns="{!v.columns}" keyField="Id" hideCheckboxColumn="true"/> </aura:component>
HyperLinkDatableController.js
({ doInit : function( component, event, helper ) { component.set('v.columns', [ { label: 'Name', fieldName: 'contacturl', type: 'url', typeAttributes: { label: { fieldName: 'Name' }, target: '_blank' }}, {label: 'Department',fieldName: 'Department', type: 'Text' }, {label: 'Lead Source',fieldName: 'LeadSource', type: 'Phone' }, {label: 'Phone',fieldName: 'Phone', type: 'Phone' }, { label: 'Account Name', fieldName: 'accounturl', type: 'url', typeAttributes: { label: { fieldName: 'AccountName' }, target: '_blank' } } ]); //getting contact records var action = component.get( "c.fetchContacts" ); action.setCallback(this, function( response ) { var state = response.getState(); if ( state === "SUCCESS" ) { var records = response.getReturnValue(); //setting value for url records.forEach( function( record ) { record.AccountName = record.Account.Name; record.accounturl = '/' + record.Account.Id; record.Name = record.Name; record.contacturl = '/' + record.Id; }); component.set( "v.conList", records ); } }); $A.enqueueAction( action ); } })
<aura:application access="GLOBAL" extends="force:slds"> <c:HyperLinkDatatable/> </aura:application>
No comments:
Post a Comment