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:


42 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
    3. Lightning is Case Sensitive. 'I' should be caps in "Id". try keyField="Id" and it'll work.

      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
  11. how to append hyperlink in lookup record to open its detail page.
    For eg :if I have Account record column in my datatable from contact component,then how can i open account record from it?

    ReplyDelete
    Replies
    1. Yes. You can do that. Check the red text in this post. Build similar attributes in the JavaScript.

      Delete
  12. Thanks for posting this. However, when clicked on the record it always opens the record in a new tab. Can someone help me to open it on the current page.

    ReplyDelete
  13. Thanks for posting this! How to open the detail page in the same tab? It always opens in the new tab.

    ReplyDelete
  14. Hi,while trying with LWC its not working.Can you please suggest.I saw your blog on LWC but that through button.I want hyperlink.Please help.

    ReplyDelete
  15. This is not working for related records. If we need to add link over related record field of account.

    ReplyDelete
    Replies
    1. It should work. For example, if you fetch Contacts and want to hyper link Account, then use AccountId and Account.Name for hyperlink.

      Delete
  16. It worked for me thanks for sharing this knowledge.
    A input if anyone searching for opening new rescord in a sub tab as per requirement change target: '_self' .rest is same.

    Happy learning:)

    ReplyDelete
  17. Hi,

    The mentioned approach works fine with classic and lightning. But When we use the same component in communities, then the URL forming is not correct.

    Example: In my partner community, a record detail page looks like
    https:///s/detail/
    but when I use this approach, the generated url is like below
    https:///s/

    Please help.

    ReplyDelete
    Replies
    1. Can you check your code?
      record.linkName = '/'+record.Id;
      This should work in Communities as well. Upgrade your Community Aura Component version and try.
      Put console.log and make sure the record.linkName = '/'+record.Id; is forming the URL correctly.

      Delete