I have a lightning web component that fetch account record from Salesforce. When a user clicks on the Account name, I want to take the user to the Account record page. How can I achieve this?
.html
<template>
<lightning-card title="Datatable styling in lwc">
<template if:true={tableData}>
<div class="myTable">
<lightning-datatable
key-field="Id"
data={tableData}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</div>
</template>
</lightning-card>
</template>
.js
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/tableController.getAccounts'
import {loadStyle} from 'lightning/platformResourceLoader'
import COLORS from '@salesforce/resourceUrl/colors'
const COLUMNS = [
{label:'Account Name', fieldName: 'Name',
type: "url",
typeAttributes: { label: { fieldName: "Id" }, target: "_top" },
cellAttributes:{
class:{fieldName:'accountColor'},
}},
{label:'Annual Revenue', fieldName: 'AnnualRevenue', type: 'currency',
cellAttributes:{
class:{fieldName:'amountColor'}
}},
{label:'Industry', fieldName: 'Industry', type: 'text'},
{label:'Phone', fieldName: 'Phone', type: 'phone'}
]
export default class DatatableDemo extends LightningElement {
tableData
column = COLUMN
...... other code
}
.cls
public with sharing class tableController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, AnnualRevenue, Industry, Phone from Account];
}
}
Best Answer
For a hyperlink you need two fields: The Name field and the Id field of whatever data you are wanting to show.
So for your Account version above, your configuration for an Account hyperlink would be:
One you have the data, you need to add another acct field - the url one:
The JSON.parse... bit is because the Acct data is immutable.
Finally, you need to use the
LinkUrl
field in the columns - note, I had the Id/Name fields the wrong way around - I've corrected above.Couple more things - you will need to assign your
COLUMNS
to a class member.