Sunday, May 15, 2022

Navigate to a record’s create page with default field values in LWC using standard action

 To launch a record’s create page with prepopulated field values we use lightning/pageReferenceUtils and lightning/navigation together.

The lightning/pageReferenceUtils module provides the encodeDefaultFieldValues() and decodeDefaultFieldValues() functions. This functions encode default field values into a string and decode them. 

With standard actions, the default field values pass through the URL to the object as a string, and the redirect and replace is handled for us. 

To encode the default field values into a string, pass them to encodeDefaultFieldValues(). Assign the encoded string to the state.defaultFieldValues property in the page reference.

Now, Let us take an example to "Launch a Contact Record with Default Field Values Using a Standard Action".


navToNewContactWithDefaultValues.html

<template>

    <lightning-button

            name="new-with-defaults"

            label="Go to New Contact Record Page with Defaults"

            onclick={navigateToNewContactWithDefaultValues}

        ></lightning-button>

</template>

navToNewContactWithDefaultValues.js

import { LightningElement } from 'lwc';

import { NavigationMixin } from 'lightning/navigation';

import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';

 

 

export default class NavToNewContactWithDefaultValues extends NavigationMixin(LightningElement) {

    navigateToNewContactWithDefaultValues() {

        const defaultValues = encodeDefaultFieldValues({

            FirstName: 'TestFName',

            LastName: 'TestLName'

       

        });

 

        console.log(defaultValues);

 

        this[NavigationMixin.Navigate]({

            type: 'standard__objectPage',

            attributes: {

                objectApiName: 'Contact',

                actionName: 'new'

            },

            state: {

                defaultFieldValues: defaultValues

            }

        });

    }

}


Now, Let us wrap our LWC comp inside aura component and place it as a standard action on contact page as shown below.

navigateToLWCAuraComp.cmp

<aura:component implements="force:lightningQuickAction">

    <c:navToNewContactWithDefaultValues></c:navToNewContactWithDefaultValues>

</aura:component>

Navigate to a record’s create page with default field values in LWC using standard action

Now, Click on action button and below window will be launched,

Navigate to a record’s create page with default field values in LWC using standard action


Now, click on button displayed in above image.

Navigate to a record’s create page with default field values in LWC using standard action

Contact record will be created once we click on submit button shown in above image.

Navigate to a record’s create page with default field values in LWC using standard action


With override actions, you are responsible for decoding the string of default field values from the URL which we will see in next post.

Saturday, May 14, 2022

How to navigate from one Lightning Web Component to another Lightning Web Component?

 In this blog post we will learn "How to navigate from one Lightning Web Component to another Lightning Web Component?".

To navigate from one LWC to another LWC we need to embed LWC in AURA component having lightning:isUrlAddressable and navigate the user from LWC to AURA component.

Let's understand this with an example.

Let's create two LWC and one AURA component.

sourceLWC --> A lwc from where we will navigate.
targetLWC --> A lwc where we will navigate.
navigateToLWCAuraComp --> An aura component containing "targetLWC " to make navigation possible.


sourceLWC .html

<template>

    <lightning-button variant="success" label="Navigate to targetLWC" onclick={navigatetotargetlwccomp}></lightning-button>

</template>


sourceLWC.js

import { LightningElement } from 'lwc';

import {NavigationMixin} from 'lightning/navigation';

 

export default class SourceLWC extends NavigationMixin(LightningElement) {

    navigatetotargetlwccomp(){

        this[NavigationMixin.Navigate]({

 

            type: 'standard__component',

   

            attributes: {

   

                componentName: "c__navigateToLWCAuraComp"

   

            },

            state: {

                c__propertyValue: '500'

            }

   

        });

    }

}


sourceLWC.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__HomePage</target>

        <target>lightning__RecordPage</target>

    </targets>

</LightningComponentBundle>

navigateToLWCAuraComp.cmp

<aura:component implements="flexipage:availableForAllPageTypes,lightning:isUrlAddressable" access="global">

    <aura:attribute type="String" name="propertyValue"/>

    <aura:handler name="init" value="{!this}" action="{!c.init}"/>

<c:targetLWC propertyValue="{!v.propertyValue}"></c:targetLWC>

</aura:component>       


navigateToLWCAuraCompController.js

({

    init: function(cmp, evt, helper) {

        var myPageRef = cmp.get("v.pageReference");

        var propertyValue = myPageRef.state.c__propertyValue;

        cmp.set("v.propertyValue", propertyValue);

    }

})


targetLWC.html

<template>

 <b>   Hi I am targetLWC component. Value from target LWC is {propertyValue} </b>

</template>


targetLWC.js

import { LightningElement,api } from 'lwc';

 

export default class TargetLWC extends LightningElement {

 

    @api propertyValue;

}


targetLWC.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__HomePage</target>

        <target>lightning__RecordPage</target>

    </targets>

</LightningComponentBundle>



Results:

How to navigate from one Lightning Web Component to another Lightning Web Component?


Click on the button "Navigate to targetLWC",

How to navigate from one Lightning Web Component to another Lightning Web Component?

Sunday, February 27, 2022

Navigation in lightning web component

 In this blog post we will learn "Navigation in lightning web component".

To generate a URL or to navigate to a page reference we use the lightning-navigation service wire adapters and functions.

CurrentPageReference :

CurrentPageReference is used to get a reference to the current page in Salesforce. As page URL formats can change in future releases, so in order to future proof our apps we use page references instead of URLs.

Syntax :

import { CurrentPageReference } from 'lightning/navigation';

@wire(CurrentPageReference)

pageRef;


NavigationMixin :

NavigationMixin adds two APIs to our component's class.

1) [NavigationMixin.Navigate](pageReference, [replace]) - A component calls this API to navigate to another page in the application.

2) [NavigationMixin.GenerateUrl](pageReference) - A component calls this API to get a promise that resolves to the resulting URL. 

The component can use the URL in the href attribute of an anchor. It can also use the URL to open a new window using the window.open(url) browser API.

Syntax :

import { NavigationMixin } from 'lightning/navigation';

export default class MyCustomElement extends NavigationMixin(

    LightningElement

) {}


navigationSampleLWC.html

<template>

    <lightning-card title="Navigate To Contact Record ">

     <lightning-button label="New Contact" onclick={navigateToNewContact}></lightning-button>

     <lightning-button label="View Contact" onclick={navigateToViewContact}></lightning-button>

     <lightning-button label="Edit Contact" onclick={navigateToEditContact}></lightning-button>

    </lightning-card>

</template>


navigationSampleLWC.js

import { LightningElement,api } from 'lwc';

import {NavigationMixin} from 'lightning/navigation';

export default class NavigationSampleLWC extends NavigationMixin(LightningElement) {

@api recordId;

// Navigate to the Contact new page

navigateToNewContact(){

    this[NavigationMixin.Navigate]({

        type: 'standard__objectPage',

        attributes: {

            objectApiName: 'Contact',

            actionName: 'new'

        },

    });

}

// Navigate to the Contact view page

navigateToViewContact(){

    this[NavigationMixin.Navigate]({

        type: 'standard__recordPage',

        attributes: {

            recordId : this.recordId,

            objectApiName: 'Contact',

            actionName: 'view'

        },

    });

}

// Navigate to the Contact edit page

navigateToEditContact(){

    this[NavigationMixin.Navigate]({

        type: 'standard__recordPage',

        attributes: {

            recordId : this.recordId,

            objectApiName: 'Contact',

            actionName: 'edit'

        },

    });

}

}


navigationSampleLWC.js-meta.xml

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

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

    <apiVersion>52.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

        <target>lightning__RecordPage</target>

    </targets>

</LightningComponentBundle>


Now, Let's add this component on contact record detail page.


Navigation in lightning web component


Sunday, February 20, 2022

How to use design attribute in LWC?

 In this blog post we will learn how we can use design attribute in LWC.

In aura component we use to have the design resource in the same folder as our .cmp resource.
Design resource controls which attributes are exposed to builder tools like the Lightning App Builder, Experience Builder, or Flow Builder. 

Now, the question is what if we want to use this with LWC? Is that possible?

Yes it is possible to we can use design attribute in LWC.

As we know LWC bundle contains an HTML file, a JavaScript file, and a metadata configuration file as shown in the below image and these files are created once we create a Lightning web component.

How to use design attribute in LWC?


A sample metadata configuration file is shown below. The configuration file defines the metadata values for the components including the design configuration which we will understand later with an example.

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

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

    <apiVersion>50.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>  // Component available for app page.
        <target>lightning__RecordPage</target>  // Component available for record detail page.
        <target>lightning__HomePage</target> // Component available for app home page.
    </targets>


</LightningComponentBundle>


So now let's understand this with an example.

We need to define the property in component javascript class using @api decorator.


designAttributeExampleLwc.html


<template>

    <lightning-card title="Design Attribute Example"> 

        Card Name: {cardName}

        <br></br>

        Card Description: {cardDescription}

    </lightning-card>

</template>



designAttributeExampleLwc.js


import { LightningElement, api } from 'lwc';

 

export default class DesignAttributeExampleLwc extends LightningElement {

    @api cardName='I am card 1';

    @api cardDescription ='This is card 1 description';

}



designAttributeExampleLwc.js-meta.xml


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

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

    <apiVersion>52.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

 

        <target>lightning__AppPage</target> 

        <target>lightning__RecordPage</target> 

        <target>lightning__HomePage</target> 

    </targets>

    <targetConfigs>

        <targetConfig targets="lightning__RecordPage,lightning__HomePage">

            <property label="Card Name" name="cardName" type="String"/>

            <property label="Card Name" name="cardDescription" type="String"/>

        </targetConfig>

    </targetConfigs>

 

</LightningComponentBundle>



Now, Let's add this component to the account record detail page as shown below.

How to use design attribute in LWC?






Saturday, January 15, 2022

Display toast notifications in Lightning Web Component

Toast notification pops up to alert users of a success, error, or warning

We need to import ShowToastEvent from the lightning/platformShowToastEvent module to

display a toast notification in Lightning Experience or Experience Builder sites.

The important point to note is ShowToastEvent isn’t supported on login pages in Experience

Builder sites.

Success Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Success Message',

            message: 'Record inserted successfully ',

            variant: 'success',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

Error Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Error Message',

            message: 'Record inserted failed ',

            variant: 'error',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

Warning Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Warning Message',

            message: 'Some problem occured ',

            variant: 'warning',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

Info Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Information Message',

            message: 'Operation running in background ',

            variant: 'info',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }


Let us understand the use with an example below.


<template>

    <lightning-card  title="Testing Toast In LWC">

        <lightning-button label="Success Toast" onclick={successToastFunction}></lightning-button>

        <lightning-button label="Error Toast" onclick={errorToastFunction}></lightning-button>

        <lightning-button label="Warning Toast" onclick={warningToastFunction}></lightning-button>

        <lightning-button label="Information Toast" onclick={informationToastFunction}></lightning-button>

    </lightning-card>

</template>



import { LightningElement } from 'lwc';

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class TestingToastInLwc extends LightningElement {

    successToastFunction() {

        const evt = new ShowToastEvent({

            title: 'Success Message',

            message: 'Record inserted successfully ',

            variant: 'success',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

    errorToastFunction() {

        const evt1 = new ShowToastEvent({

            title: 'Error Message',

            message: 'Record inserted failed ',

            variant: 'error',

            mode:'dismissible'

        });

        this.dispatchEvent(evt1);

    }

    warningToastFunction() {

        const evt2 = new ShowToastEvent({

            title: 'Warning Message',

            message: 'Some problem occured ',

            variant: 'warning',

            mode:'dismissible'

        });

        this.dispatchEvent(evt2);

    }

 

    informationToastFunction() {

        const evt3 = new ShowToastEvent({

            title: 'Information Message',

            message: 'Operation running in background ',

            variant: 'info',

            mode:'dismissible'

        });

        this.dispatchEvent(evt3);

    }

}


Add this LWC on the Home Page as shown below to test it.

Display toast notifications in Lightning Web Component