Saturday, August 6, 2022

How to add custom link in data table in LWC?

 In this blog post we will see How to add custom link in data table in LWC?

Let us display the account details using data table, we will add hyper link to Account Name so that user can click and navigate to account detail page.



The below code will display columns without hyper link as shown.


const columns=[

{label: 'Account Name', fieldName: 'Name'},

{label: 'Account Industry', fieldName: 'Industry'},

{label: 'Account Description', fieldName: 'Description'},

];


How to add custom link in data tae in LWC?




In order to add hyper link to a column we need to add the typeAttributes property as shown below and assign Name to fieldName property as highlighted in 

const columns=[
{label: 'Account Name', fieldName: 'Account_URL', type: 'url', typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'} },
{label: 'Account Industry', fieldName: 'Industry'},
{label: 'Account Description', fieldName: 'Description'},

];

Assign Account_URL to fieldName and type as 'url' as highlighted in yellow.

Now, let us understand with an example,

testLWCTableExample.html

<template>

    <h1>Account Data Table</h1>

<template if:true={accList}>

    <lightning-datatable

        key-field="id"

        data={accList}

        columns={columns} >

        </lightning-datatable>

</template>

<template if:true={error}>

 Some error occured.

</template>

 </template>

testLWCTableExample.js

import { LightningElement, track, wire } from 'lwc';

import getAccountList from '@salesforce/apex/AccountDataController.getAccountList';

const columns=[

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

{label: 'Account Industry', fieldName: 'Industry'},

{label: 'Account Description', fieldName: 'Description'},

{label: 'Parent Account Name', fieldName: 'Parent_Account_Name'},

];

 

export default class TestLWCTableExample extends LightningElement {

    @track error;

    @track columns = columns;

    @track accList;

    @wire (getAccountList) accList({error, data})

    {

        if(data)

        {

            let accParsedData=JSON.parse(JSON.stringify(data));

            let baseUrlOfOrg= 'https://'+location.host+'/';

            accParsedData.forEach(acc => {

                if(acc.ParentId){

                acc.Parent_Account_Name=acc.Parent.Name;

                acc.Account_URL=baseUrlOfOrg+acc.Id;

                }

            });

            this.accList = accParsedData;

        }

        else if(error)

        {

            this.error = error;

        }

    }

   

}

testLWCTableExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>55.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__RecordPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

AccountDataController.cls

public with sharing class AccountDataController {

    @AuraEnabled(cacheable=true)

    public static list<Account> getAccountList(){

 

        list<Account> acclist=new list<Account>();

        acclist=[SELECT id,Name,Industry,Description from Account Limit 10];

        return acclist;

    }

    public AccountDataController() {

 

    }

}

Now, Let add the component to Account Record detail page to see the output:

How to add custom link in data tae in LWC?

How to display lookup field in lightning data table in LWC?

In last blog post we see how to display values in data table in LWC. In this blog post we will see how to display lookup field in data table in LWC.

Now, let us understand the real time use of data table with an example below where we will display account records and additionally we will display the Parent Account Name as shown below.



How to display lookup field in lightning data table in LWC?



testLWCTableExample.html

<template>

    <h1>Account Data Table</h1>

<template if:true={accList}>

    <lightning-datatable

        key-field="id"

        data={accList}

        columns={columns} >

        </lightning-datatable>

</template>

<template if:true={error}>

 Some error occured.

</template>

 </template>



Note:

The data which we received from wire method is read only data and hence to display lookup values
we need to parsed data. We can use JSON.stringify to remove the reference as shown below. Once we remove the reference the data will not be read only and a new variable can now be add to the result to hold lookup values.

testLWCTableExample.js

import { LightningElement, track, wire } from 'lwc';

import getAccountList from '@salesforce/apex/AccountDataController.getAccountList';

const columns=[

{label: 'Account Name', fieldName: 'Name'},

{label: 'Account Industry', fieldName: 'Industry'},

{label: 'Account Description', fieldName: 'Description'},

{label: 'Parent Account Name', fieldName: 'Parent_Account_Name'},

];

 

export default class TestLWCTableExample extends LightningElement {

    @track error;

    @track columns = columns;

    @track accList;

    @wire (getAccountList) accList({error, data})

    {

        if(data)

        {

            let accParsedData=JSON.parse(JSON.stringify(data));

            accParsedData.forEach(acc => {

                if(acc.ParentId){

                acc.Parent_Account_Name=acc.Parent.Name;

                }

            });

            this.accList = accParsedData;

        }

        else if(error)

        {

            this.error = error;

        }

    }

   

}


testLWCTableExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>55.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__RecordPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>


Sunday, July 24, 2022

Data Table in LWC

 lightning-datatable displays tabular data where each column renders the content based on the data type. This component implements styling from the data tables blueprint in the Salesforce Lightning Design System.

lightning-datatable is not supported on mobile devices. Supported features include:

  • Displaying and formatting of columns with appropriate data types
  • Inline editing for some data types
  • Header actions
  • Row-level actions
  • Resizing of columns
  • Selecting of rows
  • Sorting of columns by ascending and descending order

Tables can be populated during initialization using the data, columns, and key-field attributes.            The key-field attribute is required for correct table behavior. It associates each row with a unique identifier.

The below example creates a table whose first column displays a checkbox for row selection. The checkbox column is displayed by default, and you can hide it by adding hide-checkbox-column in your markup. Selecting the checkbox selects the entire row of data and triggers the onrowselection event handler.

<template>

    <lightning-datatable

        data={data}

        columns={columns}

        key-field="id"

        onrowselection={getSelectedName}

    >

    </lightning-datatable>

</template>


Now, let us understand the real time use of data table with an example below where we will display account records.

testLWCTableExample.html

<template>

    <h1>Account Data Table</h1>

<template if:true={accList}>

    <lightning-datatable

        key-field="id"

        data={accList}

        columns={columns} >

        </lightning-datatable>

</template>

<template if:true={error}>

 Some error occured.

</template>

 </template>

testLWCTableExample.js

import { LightningElement, track, wire } from 'lwc';

import getAccountList from '@salesforce/apex/AccountDataController.getAccountList';

const columns=[

{label: 'Account Name', fieldName: 'Name'},

{label: 'Account Industry', fieldName: 'Industry'},

{label: 'Account Description', fieldName: 'Description'},

];

 

export default class TestLWCTableExample extends LightningElement {

    @track error;

    @track columns = columns;

    @track accList;

    @wire (getAccountList) accList({error, data})

    {

        if(data)

        {

            this.accList = data;

        }

        else if(error)

        {

            this.error = error;

        }

    }

   

}

testLWCTableExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>55.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__RecordPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

AccountDataController.cls

public with sharing class AccountDataController {

    @AuraEnabled(cacheable=true)

    public static list<Account> getAccountList(){

 

        list<Account> acclist=new list<Account>();

        acclist=[SELECT id,Name,Industry,Description from Account Limit 10];

        return acclist;

    }

    public AccountDataController() {

 

    }

}

Now, Let add the component to Account Record detail page to see the output:

Data Table in LWC


Displaying Currency and Percentages:

Currency type displays a value based on the org currency and our Salesforce locale by default.To override the default currency code, pass in a custom currencyCode value as shown below.

To customize our output, pass in the attributes of the base component via the typeAttributes property. Not all attributes on a base component are supported. 


const columns = [

    {

        label: 'Amount',

        fieldName: 'amount',

        type: 'currency',

        typeAttributes: { currencyCode: 'INR' },

    },

];


Displaying Date and Time Using Type Attributes:


The locale set in the Salesforce user preferences determines the default formatting for date and time types.

The data table supports the date object and dates provided as ISO8601 formatted strings. Timestamps are not supported. 

The default format is July 24, 2022.

While the date type can be used to display date and time, the date-local type displays only the date. Here's how you can display Salesforce date and time data types in lightning-datatable.

Data Table in LWC

Example 1:

{
        label: "Date",
        fieldName: "DueDate",
        type: "date-local",
        typeAttributes:{
            month: "2-digit",
            day: "2-digit"
        }
}

Output: 07/24/2022


Example 2:

{
        label: "Closed Date",
        fieldName: "ClosedDate",
        type: "date",
        typeAttributes:{
            weekday: "long",
            year: "numeric",
            month: "long",
            day: "2-digit"
        }
}

Output: Sunday, July 24, 2022

Example 3:

{
        label: "Arrival Time",
        fieldName: "ArrivalTime",
        type: "date",
        typeAttributes:{
            year: "numeric",
            month: "long",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit"
        }
}

Output: July 24, 2022, 12:00 PM

Example: 4

{
        label: "Event Time",
        fieldName: "EventTime",
        type: "date",
        typeAttributes:{
            weekday: "long",
            year: "numeric",
            month: "long",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit"
        }
}

Output: Sunday, July 24, 2022, 12:00 PM

Sunday, June 5, 2022

How to use static resource in LWC?

In this blog post we will learn how we can use static resource in LWC.

First create "testingstaticresourcewithLWC" zip file with the img folder as shown below.


How to use static resource in LWC?

This file has the below folders, 

staticresourcetest  which further has testimage under it as a PNG file.

How to use static resource in LWC?


 
How to use static resource in LWC?


Now, let us try to get this is LWC.

staticresourceLWC.html

<template>

    <lightning-card title="Static Resource Test">

     <img src={extractedimgfromLWC}>

    </lightning-card>

</template>


staticresourceLWC.js

import { LightningElement } from 'lwc';

import resource_test from '@salesforce/resourceUrl/testingstaticresourcewithLWC';

export default class StaticresourceLWC extends LightningElement {

    extractedimgfromLWC = resource_test + '/staticresourcetest/testimage';

}


staticresourceLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>54.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__RecordPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>


Now, let us try to add this Account page to see the results.

How to use static resource in LWC?


Sunday, May 22, 2022

How to access custom labels In Lightning Web Component?

 We import label using  @salesforce/label scoped module. 

Syntax:

import labelName from '@salesforce/label/labelReference';

Where,

labelName—A name that refers to the label.

labelReference—The name of the label in your org in the format namespace.labelName.


Let us understand with the below example,

Create 2 label as shown below.




custom labels In Lightning Web Component


custom labels In Lightning Web Component

customLabelLWC.html

<template>

    <lightning-card title={label.lightningcardname}>

     <lightning-button label={label.buttonnamefromcustomlabel}> </lightning-button>

    </lightning-card>

</template>


  customLabelLWC.js

import { LightningElement } from 'lwc';

import lightningcardname from '@salesforce/label/c.lightningcardname';

import buttonnamefromcustomlabel from '@salesforce/label/c.buttonnamefromcustomlabel';

export default class CustomLabelLWC extends LightningElement {

label ={lightningcardname,buttonnamefromcustomlabel}

 }

customLabelLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>54.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__RecordPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>


Now, add this component to Account page to see the result.

How to access custom labels In Lightning Web Component?