July 27, 2018

How to Hyperlink a Record in lightning:datatable?

Sample Code:

Component:

<aura:component implements="force:appHostable"
    controller="AccountListController">
                
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    
    <lightning:datatable data="{! v.acctList }" 
                         columns="{! v.mycolumns }" 
                         keyField="id"
                         hideCheckboxColumn="true"/>
    
</aura:component>

Component Controller:

({
    
    fetchAccounts : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'linkName', type: 'url', 
            typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            {label: 'Industry', fieldName: 'Industry', type: 'text'},
            {label: 'Type', fieldName: 'Type', type: 'Text'}
        ]);
        var action = component.get("c.fetchAccts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var records =response.getReturnValue();
                records.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                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 FROM Account LIMIT 10 ];
        
    }
    

}

Output:


26 comments:

  1. Thanks the URL functionality is working but I am getting Id's instead of Names under the Account name Column. Please Help

    ReplyDelete
    Replies
    1. you need to set the Link value and Link label.

      {label: 'Account Name', fieldName: 'linkName', type: 'url',
      typeAttributes: {label: { fieldName: 'Name' },value:{fieldName: 'linkName'}, target: '_blank'}
      },

      It Worked for me

      Delete
  2. I am using sorting along with this code. It is not working. Can you please display helper link on your sorting post. http://www.infallibletechie.com/2018/03/lighting-data-table-sorting-example.html

    ReplyDelete
  3. Hi Magulan,

    Thank You! for your reply. While using hyper link on Account name, field name you are passing account Id and in type attribues you are passing actual name of account. While sorting clicked it is taking field name as account Id not account name. So sorting functionality is behaving differently. Can you please help me to pass name instead of Id on sorting while we are using hyper link or button on name field.

    ReplyDelete
    Replies
    1. Check this - https://www.infallibletechie.com/2019/01/lighting-data-table-sorting-while-we.html

      Delete
  4. Hi Magulan,

    Thank You! For your reply. Its helped great for me. I am appreciating your reply and your dedication, hard work on salesforce.

    ReplyDelete
  5. For me...account name is not displaying

    ReplyDelete
    Replies
    1. Check the JS code. Make sure you are setting the field correctly in that.

      Delete
  6. Thanks! this method of achieving the functionality worked for me

    ReplyDelete
  7. Hi Magulan,
    Here is my apex class code in salesforce classic:-

    static testMethod void emailAddressNotConfirmed() {

    VSO_Settings__c vso=new VSO_Settings__c(Site_URL__c='https://tpt-vso.cs87.force.com',Site_Path__c='/jobopportunities');
    insert vso;



    my question is how can i implement this hardcoded url of apex class in salesforce lightning.?

    ReplyDelete
    Replies
    1. Check the below links
      http://www.infallibletechie.com/2018/08/how-to-get-domain-url-using-apex-in.html
      http://www.infallibletechie.com/2016/08/how-to-get-base-url-in-visualforce.html

      Delete
  8. I don't understand how javascript understands id attribute of the record. for me record.id comes as undefined. Any pointers please? I have used the same changes as highlighted in the example of this blog.

    ReplyDelete
    Replies
    1. Make sure keyField="id" is added to lightning:dataTable and Id is included in the SOQL.

      Delete
    2. I also used the same way and keyField="id" and Id in SOQL are in place. but still getting ID as undefined.

      Delete
  9. How we can do similar functionality in LWC? When I try to add hyperlink field value dynamically in LWC, it doesn't allow. Could you please help me on this.

    ReplyDelete
    Replies
    1. Check this - http://www.infallibletechie.com/2019/06/lightningdatatable-with-buttons-in.html

      Delete
  10. Uncaught Error in $A.getCallback() [records.forEach is not a function] . Why this comes as an error?

    ReplyDelete
    Replies
    1. Make sure records variable is defined and the return value is not null. Do a null check before var records =response.getReturnValue();
      records.forEach(function(record){
      record.linkName = '/'+record.Id;
      });

      Delete
    2. I think it has to do with this syntax: Array.from(records).forEach(function(record){}. It doesnt hit an error now but I cant receive results either on this field.

      Delete
    3. put debug log and check whether apex class is returning results.

      Delete
    4. BTW, i found it (And i thank you very much for your thoughts here):

      Array.from(results.Schedules).forEach(function(Schedule){
      Schedule.ProductName = schedule.OpportunityLineItem.Product2.Name__c;
      });

      Delete