SFDC Stop - Always the latest about Salesforce


Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.


Telegram logo   Join our Telegram Channel
Showing posts with label Lightning Tutorial. Show all posts
Showing posts with label Lightning Tutorial. Show all posts

Monday, 15 January 2024

Embed screen flow in LWC component: Pass data to screen flow and Receive data from Screen Flow

Hello Trailblazers,


You might have come across the below blog posts published by me in the past:

  1. How to pass data from lwc to screen flow in salesforce?
  2. How to pass data from screen flow to lwc in salesforce?


You might be thinking, what the heck are we doing in this post then???


Give me a moment to clarify: In the above posts, we actually embedded a LWC component within a screen flow and passed data to it/received data from it. However, in today's post, we're going to do exactly the opposite. We're going to embed a screen flow within a LWC component and pass data to screen flow, receive data from screen flow. We're going to use lightning-flow lwc component provided by salesforce in this tutorial. So, without spending much time on discussion. Let's begin!


First of all we're going to create a very basic LWC component called flowContainer which will have our flow. We're going to embed this component on the homepage just like other demo components which we created. The content of .meta-xml file for the same is provided below:

flowContainer.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Flow Container</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Screen Flow - Duplicate Contacts

Before jumping on to more LWC code, let's create our screen flow first. This flow, named as Duplicate Contacts, is going to do the following:

  1. Get the list of contact ids from flowContainer LWC
  2. Create a new account record
  3. Query the existing contact records using their ids, create a copy of those, tag them to the new account record and insert them in salesforce
  4. Pass the new account record id to flowContainer LWC

Follow the below steps to create our screen flow:

1. Go to setup. Search for flow and click the New Flow button

2. In the new flow screen, choose Screen Flow option and click Create

3. In the Toolbox on the left hand side, click New Resource. The inputs are provided below:
      Resource Type: Variable
      API Name: ids
      Description: List of contact ids
      Data Type: Text
      Availability Outside the Flow: Available for input

We basically created a collection variable ids here, which will receive the list of contact ids from our flowContainer LWC component. We checked Available for input as we're going to receive it's value from outside the flow i.e. from our LWC component.

Note: No need to check these boxes otherwise. I've seen a lot of developers checking both Available for input and Available for output boxes without any reason. Please see if you really need an input in this variable from somewhere outside the flow and then only check this checkbox.

Before moving ahead, let's save the flow using the Save button on the top right. Click the Save button, fill in the details as shown below and click the save button present on the popup again to save the flow.
      Flow Label: Duplicate Contacts
      Flow API Name: DuplicateContacts
      Description: This flow will duplicate existing contact records based on ids and link them with a new account record

Inside this flow, we want to have a screen first which will create a new Account record. But before that, we need a resource of type Variable and object as Account. The details of the new resource is provided below:
      Resource Type: Variable
      API Name: NewAccount
      Description: This variable will store the new account record which is created
      Data Type: Record
      Object: Account

The screen to create a new account is provided below:

The header is: Enter Account Details
We added a single textbox in this screen which will store the Account Name as provided below:

Note that we switched to the Fields tab, populated the RecordVariable with our NewAccount variable that we created before and then we dragged + dropped the Account Name field to the screen. This will automatically bind the value entered by the user to the Name field of our NewAccount variable.

Now, we can add the Create Records element to our flow in order to insert this new account record. The details of Create Records element are provided below:
      Label: Create Account
      API Name: Create_Account
      Description: Insert the account record present in NewAccount variable in salesforce
      How Many Records to Create: One
      How to Set the Record Fields: Use all values from a record
      Record: NewAccount
Once our account record is created, we need to duplicate contact records and attach them to this new account record. In order to do it, we're going to use our Get Records element to query the contact records using ids. The details are provided below:
      Label: Query Contacts
      API Name: Query_Contacts
      Description: Query contact records based on record ids passed to the flow
      Object: Contact
      Filter: Id In {!ids}
      Sort Order: Not Sorted
      How Many Records to Store: All records
      How to Store Record Data: Automatically store all fields
If you notice above, we're using the {!ids} variable here which will have the ids of our existing contact records to query them. Now, we're going to remove the Id from these contact records to create new records, tag them to the newly created account and store them in a list.

In order to do that, we need a Loop element using which we'll loop all the queried contacts. The details of the same are provided below:
      Label: Iterate Contacts
      API Name: Iterate_Contacts
      Description: Iterate the queried contacts
      Collection Variable: {!Query_Contacts}
      Direction: First item to last item

Let's create a new list first to store our modified contact records which we're going to insert. The details are provided below:
      Resource Type: Variable
      API Name: contactsList
      Description: List of contact records
      Data Type: Record
      Object: Contact
      Allow multiple values (collection): True

Now, inside this loop, we'll set the Id and AccountId for every contact using an assignment element and add that contact record to a new list of contacts: contactsList which we created before.

The details for the same are as follows:
      Label: Set Id and AccountId
      API Name: Set_Id_and_AccountId
      Description: Set Id as empty and AccountId using the Id of newly created account for the current contact record
      Variable values:
      {!Iterate_Contacts.Id} <Equals> <Blank>
      {!Iterate_Contacts.AccountId} <Equals> {!NewAccount.Id}
      {!contactsList} <Add> {!Iterate_Contacts}

After this screen we'll use the Create Records element to insert contactsList in salesforce. The details for the same are provided below:
      Label: Create Contacts
      API Name: Create_Contacts
      Description: Insert the list of newly created contact records in salesforce
      How Many Records to Create: Multiple
      Record Collection: contactsList


One thing that we should update here is our NewAccount variable. We want to redirect the user to the newly created account record from our flowContainer LWC component. That means, we need to pass the new account from flow to LWC. Therefore, we can set Availability Outside the Flow as Available for output as shown below:

Now, our flow is complete. Make sure to Activate the flow. It's time to move on to the html code for our LWC component.

flowContainer.html

This component will basically show a button, which will launch our screen flow. Let's see the code:
<template>
    <template lwc:if={showFlow}>
        <lightning-flow
            flow-api-name="DuplicateContacts"
            flow-input-variables={inputVariables}
            onstatuschange={handleStatusChange}>
        </lightning-flow>
    </template>
    <template lwc:else>
        <lightning-button label="Duplicate Contacts" onclick={launchFlow}></lightning-button>
    </template>
</template>
As you can see above, we have two templates rendered on the basis of a boolean showFlow which is used in lwc:if attribute added in a template tag. If showFlow is true, we're displaying the DuplicateContacts screen flow in our lwc component using lightning-flow tag. If you notice inside lightning-flow tag, we've specified value for 3 attributes:

  1. flow-api-name: This should be the API name of the flow. For our flow, it's DuplicateContacts.
  2. flow-input-variables: This refers to the array of input variables i.e. the flow variables whose values we're going to pass from this LWC component.
  3. onstatuschange: We're capturing the statuschange event here and calling our handleStatusChange method. statuschange event is fired whenever the status of the flow is changed. For example: when the flow is started/paused/finished etc.

We're going to define showFlow, inputVariables - variables and handleStatusChange method in our js file. In the lwc:else section, we have a lightning-button whose label is Duplicate Contacts and on clicking of that button we're calling our launchFlow method which we're going to define in our js file which will launch our flow. So, let's move on to our js file to complete this component.

flowContainer.js

This is the most important part of the tutorial as this is where we're going to pass data from LWC to screen flow and we're going to receive data from screen flow in our LWC component. Let's take a look at the code below:
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class FlowContainer extends NavigationMixin(LightningElement) {

    // * Boolean to display/hide flow
    showFlow = false;

    // * Ids of contact records to be passed to flow
    contactIds = [
        '003H3000001l11BIAQ',
        '003H3000001l11AIAQ',
        '003H3000001l112IAA'
    ];

    // * Input variables to pass to flow from LWC
    inputVariables = [
        {
            name: 'ids',
            type: 'String',
            value: this.contactIds
        }
    ]

    /**
     * @description This method is used to launch the flow from lwc
     */
    launchFlow() {
        this.showFlow = true;
    }

    /**
     *
     * @param {object} event status change event - received when flow state is changed
     * @description This method will be called whenever the state of the flow is updated
     */
    handleStatusChange(event) {
        if(event.detail.status === 'FINISHED') {
            let accountVariable = event.detail.outputVariables?.find(
                outputVariable => outputVariable.name === 'NewAccount'
            );
            this.navigateToRecordPage(accountVariable.value.Id);
        }
    }

    /**
     *
     * @param {string} recordId Id of the record
     * @description This method is used to navigate the current user to the detail page of the record whose id is passed as parameter
     */
    navigateToRecordPage(recordId) {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: recordId,
                actionName: 'view',
            },
        });
    }
}
Let's understand the above code line by line. First of all we imported NavigationMixin from lightning/navigation library. We're going to navigate to the record page of our newly created account record using this method. We also updated our FlowContainer class to extend NavigationMixin(LightningElement) for the same purpose.

We introduced three variables in our js file:

The first one is showFlow, which is a boolean variable and is false by default. This variable will be toggled to true when we want to display the flow in our LWC component. Remember the lwc:if condition in our HTML which is using this variable? If you check the HTML again you'll notice that by default our lightning-button will be visible through the lwc:else condition as showFlow is false.

The second one is contactIds, which is a string array that consist of the ids of contact records. We're going to pass this array to our flow ids variable.

The third one is inputVariables array, which is passed to our lightning-flow's flow-input-variables attribute. This is basically an array of objects, where each object is having a name, a type and a value. For each variable that we want to populate in our flow, through our LWC, we should have an entry for that in this array.

In each object inside our inputVariables array:
  • The name should be the name of the variable as defined in our flow. For our entry it's ids as we defined ids variable in the flow which will store the contact ids.
  • The type is the data type of the variable. In our case it's String (Text in flow)
  • The value should be the value of the variable defined in our flow. For our scenario, we want to pass the list of contact ids as value to our ids variable. Therefore, we've referred to our contactIds variable here which is defined above in the js and passed that as the value for our ids flow variable.

Note: I'm re-iterating the same thing so that you don't miss this. If you notice, this is the point where we've defined that: in the ids variable of our screen flow, we want to pass the array of contact ids we've hardcoded in our js. This value can come from different sources depending upon your use case. For example: You can have a lightning-datatable where you can select some records and as the records are selected, you can populate the contactIds array. This array will automatically be passed to the ids variable in the flow as the flow is launched. 

After that we've defined 3 methods which are as follows:

  1. launchFlow(): This method will be called when we click Duplicate Contacts button in our HTML. It'll set showFlow attribute to true which will automatically hide the button and will show the screen flow in our LWC. In a way we can say, this method is used to launch our screen flow.

  2. handleStatusChange(event): This method will be called whenever the flow status is updated. It's binded to statuschange event of our lightning-flow component. Inside this method, we need to check: If the flow is finished, we need to redirect the user to the detail page of newly created account record. We're receiving event inside this method as a parameter so, we're basically checking here if: event.detail.status === FINISHED i.e. if the flow is finished, we're referring to the outputVariables in our flow using event.detail.outputVariables to get the newly created account record.

    Remember that Available for output checkbox which we checked in our NewAccount variable inside the flow? That was marked so that it's value can be accessed outside the flow. Therefore, that variable will be received in the array of our ouputVariables accessed through event.detail.outputVariables.

    I'm sharing the NewAccount flow variable below again for your reference:
    As you can notice, we marked this as Available for output so that we can receive the value of this variable outside the flow i.e. in our case - inside our flowContainer lwc component. If you log event.detail.outputVariables, you'll get an array as shown below:
    As you can see above, there is only a single entry in this array and that is for our NewAccount variable. It's name property is having a value as NewAccount, it's objectType is Account. This variable is not a collection so isCollection is false. It's coming from flow DuplicateContacts so the flow name is the same and it's dataType is SOBJECT as it stores the value of an sObject record. Moving onto the value property, as we only populated the name of the account while creating the record from flow, it's value is an object having only two properties: Id and Name.

    Moving back to our code, we are using find() method to find the outputVariable from our outputVariables array where name = NewAccount. This will return us the first entry of our array. We're storing this in a js variable named accountVariable. Finally, we're accessing this account record's id using accountVariable.value.Id and passing it to our navigateToRecordPage() method which will navigate the current user to the new account's record page.

    Note: This is the point where we're receiving data from flow in our LWC component. The variables present in our flow which are marked as available for output, will be received in our LWC component inside outputVariables array under our event.

  3. navigateToRecordPage(recordId): This method is used to navigate the current user to the detail page of the record whose record id is passed as a parameter. This method is called from handleStatusChange() method. We're using NavigationMixin.Navigate to navigate to the standard record page and we're passing recordId as the value to our recordId attribute.

That's all for our js part as well! Let's embed our component inside the homepage and see how it works. Take a look at the demo below:
As you can see above, as we clicked on Duplicate Contacts button in our LWC, the screen flow launched. We entered the account name in the screen flow which created a new account named My Account and all the 3 contacts (whose ids we hardcoded in our js) are duplicated and attached to this new account record. We finally received this new account record in our js as the flow finished and navigated to the account detail page using our LWC.

If you see below, we have all the 3 newly created contacts linked to the same My Account record, however the old contacts are present as is and linked to their own account records.

That's all for this tutorial, I hope you liked it. Let me know your feedback in the comments down below.

Happy Trailblazing!!

Sunday, 7 January 2024

Log LWC Event Messages using Lightning Logger : Event Monitoring in Salesforce

Hello Trailblazers,

In this post we're going to talk about lightning/logger module. This module can be used to log messages to salesforce event monitoring from your lightning web components. You can log the error messages as well as any kind of interactions that a user is having with your LWC component. Let's see how!

A simple LWC component logging a message using Salesforce Event Monitoring on button click

Before jumping onto the code, I just want to share a one liner about Salesforce Event Monitoring. Event Monitoring is basically a tool (EventLogFile object) in salesforce that you can use to monitor events in your org and keep your data secure. It can track different types of events like: login, logout, web clicks, apex executions, report exports etc. You can also enable event monitoring for your custom LWC components and can use the library to log events in this EventLogFile object. You can learn more about event monitoring in this trailhead module.

Turn on Event Monitoring for LWC

In order to turn on event monitoring for lightning web components, we can go to Setup->Event Monitoring Settings and turn on the switch for Enable Lightning Logger Events as shown below:
Make sure Generate event log files switch is turned on as well.

Note: As per salesforce documentationThis change is available to customers who purchased Salesforce Shield or Salesforce Event Monitoring add-on subscriptions.

Let's begin by creating our LWC component:

eventLogDemo.html

I created a new LWC component named eventLogDemo. The HTML code for the same is provided below:
<template>
    <lightning-button label="Click Me!" onclick={createEventLog}></lightning-button>
</template>
As you can see above, I defined a simple button with label Click Me! and on clicking of this button, I'm calling my createEventLog() method which we're going to define in our js

eventLogDemo.js

import { LightningElement } from 'lwc';
import { log } from 'lightning/logger';

export default class EventLogDemo extends LightningElement {

    createEventLog() {
        log('Click Me button clicked!');
        console.log('Event Log created!');
    }
}
For the js part, first of all, I imported log method from lightning/logger library. Inside our EventLogDemo class, I defined createEventLog() method which we're calling on clicking the button. This method is calling the log method we imported from the module and is passing a string message in the parameter i.e. Click Me button clicked!. After that, we're having a console.log statement as Event Log created! which is the message printed on the console.

eventLogDemo.js-meta.xml

We also did common changes in our meta.xml file to embed this component in our homepage as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Event Log Demo</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now, it's time to do see this in action. Let's begin!

Demo

I enabled Debug Mode for my user, so that I can see additional console.logs as well along with the one I have in my component. You can do the same by navigating to Setup -> Debug Mode and enabling it for your user as shown below:
I embedded my component on the homepage and as I clicked on the Click Me! button, I received an output as shown below:
If you notice above, as I called log() method from the logger module, a message from client.js is printed on the console (because I have lightning components debug mode enabled). This object has the message as Click Me button clicked! which is the same that I passed in log() method. After this, we have our console.log() message printed as well i.e. Event Log created!.

Now, In order to view our event logs, we can query them using the below query:
SELECT Id, EventType, CreatedDate, LogFileLength, LogDate, ApiVersion, LogFileContentType, Sequence, Interval, LogFile FROM EventLogFile WHERE Interval = 'Hourly' AND EventType = 'LightningLogger'

I've mentioned Interval = 'Hourly' AND EventType = 'LightningLogger' to get only those event logs which are created using our LWC component. The result is provided below:

Note: I'm using a scratch org and it took somewhere about 2 hours for logs to start appearing after I generated them by clicking the button (the interval is Hourly for these). It might not be the same case for a production org (maybe you can check this and let me know in the comments down below). However, in the Event Monitoring Trailhead, it's written that An event log file is generated when an event occurs in your organization and is available to view and download after 24 hours. So you might have to wait more before you can access the event log files. It's also written that - all log files have 1 day data retention, you can increase it to 30 days for enterprise, unlimited and performance edition at an extra cost.

If you want to download this log file, you can do that by calling the API as shown in the LogFile column as: /services/data/v59.0/sobjects/EventLogFile/0AT1y0000053cjXGAQ/LogFile. You can also download the same using Salesforce Event Log File Browser tool.

Note: Salesforce Event Log File Browser is not an official salesforce tool.

Salesforce Event Log File Browser

To use this tool, go to: https://salesforce-elf.herokuapp.com
You can click on Production Login if you're using a developer/production org or Sandbox Login if you're using a sandbox/scratch org. You'll get the OAuth screen as shown below:
Click on Allow

You'll land to the below page where you can see all the event logs:
You can filter the results using the dropdowns/picklists present above. As you can see below, I selected the event type as LightningLogger and got the below output:
In the Action column, I have two buttons. I can download the CSV log file or a shell script - which will download the log file to my system. I downloaded the CSV log file and the output for the same is shown below:
If you notice above, the PAGE_URL is /lightning/page/home which specifies that this log is triggered from our homepage as the lwc component is embedded in the homepage and the MESSAGE is: Click Me button clicked! which is the same as we passed to the log() method. The 3 entries here means that I clicked this button (or fired this event) 3 times during the hour for which this log file is generated. We can also pass a js object to our log method which is automatically stringified. The maximum string length is 4096 characters. I modified our js code a little bit to pass an object as shown below:
import { LightningElement } from 'lwc';
import { log } from 'lightning/logger';

export default class EventLogDemo extends LightningElement {

    msg = {
        type: "click",
        action: "Click Me button clicked"
    };

    createEventLog() {
        log(this.msg);
        log('Click Me button clicked!');
        console.log('Event Log created!');
    }
}
As you can see above, I'm passing the msg object to the log() method which consist of two properties: type and action. The type is click and action is Click Me button clicked. As I click the button now, I get two messages from client.js along with my console.log() message as shown below:
This time we have two event logs generated. One is having the message as: "{"type":"click","action":"Click Me button clicked"}" and another one is having the message as "Click Me button clicked!". The log file generated for the same is provided below:
As you can see, this time our whole object is also coming as message in the logs.

This is how, you can log your custom LWC event messages and view them using salesforce event monitoring tool. That's all for this tutorial, I hope you liked it. Let me know your feedback in the comments down below.

Happy Trailblazing!!

Sunday, 31 December 2023

LWC Lookup Component by Salesforce: Lightning Record Picker

Hello Trailblazers,


In this post, we're going to learn about lightning-record-picker which is basically an input field using which you can search for salesforce records. The basic code to implement the same is provided below:

<template>
    <lightning-card hide-header label="Account Record Picker Card">
        <p class="slds-var-p-horizontal_small">
            <lightning-record-picker
                label="Select Account"
                placeholder="Type Something..."
                object-api-name="Account"
            ></lightning-record-picker>
        </p>
    </lightning-card>
</template>


As you can see above, I used the lightning-record-picker tag where I've setup the label as Select Account, the placeholder is Type Something... and the object-api-name is Account. You can ignore the lightning-card. I've added that only for a good white background as we're going to embed this component in our homepage. The result is shown below:



We also did common changes in our meta.xml file to embed this component in our homepage as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Record Picker Demo</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now, it's time to do some more changes. Let's begin!

Add filter to our lookup component

Let's add a default filter to our record picker component such that it'll search only those accounts whose Rating is equal to Warm. It's time to update our js file now:

import { LightningElement } from 'lwc';

export default class RecordPickerDemo extends LightningElement {

    filter = {
        criteria: [
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Warm'
            }
        ]
    };

}

As you can see above, we defined a filter object that consist of a single property named criteria. This property is an array which can have multiple objects, each having 3 properties:


1. fieldPath: API name of the field for the current object on which we've our record picker. You can also mention relationships upto one level, for example: Parent.Rating (considering the account object)


2. operator: It can have different values depending upon the comparison we want to perform. The possible values are given below:


eq = Equal

ne = Not Equal

lt = Less Than

gt = Greater Than

lte = Less than or equal

gte = Greater than or equal

in = Similar to IN operator of SOQL

nin = Similar to NOT IN operator of SOQL

like = Similar to LIKE operator of SOQL

includes = Check the result should include provided values

excludes = Check the result should exclude provided values


Different keywords provided above are applicable for fields of different data types. The fields and the operator values they support are provided in the salesforce documentation here. If you want to learn more about the keywords, you can check them in the GraphQL documentation here


3. value: Value for the applied filter


The updated html code to apply the filter we defined in js is provided below:

<template>
    <lightning-card hide-header label="Account Record Picker Card">
        <p class="slds-var-p-horizontal_small">
            <lightning-record-picker
                label="Select Account"
                placeholder="Type Something..."
                object-api-name="Account"
                filter={filter}
            ></lightning-record-picker>
        </p>
    </lightning-card>
</template>

Notice that we've populated filter property of our lightning-record-picker with the filter variable that is defined in our js.

With this Rating filter applied by default, we can only see a subset of records. As you can see below, only 4 account records are present in my org with Rating as Warm

If I search in my lookup now, the search is performed with this predefined Rating filter already applied to my record picker:


As you can see above, only these 4 records are visible as I search with keyword o

We can also specify a filterLogic property in our filter object. This property basically consist of logic to combine multiple filter criterias. For example: If in the current filter, we want to consider Cold rating as well, along with Warm rating, we can update our filter as shown below:
import { LightningElement } from 'lwc';

export default class RecordPickerDemo extends LightningElement {

    filter = {
        criteria: [
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Warm'
            },
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Cold'
            }
        ],
        filterLogic: '1 OR 2'
    };

}
As you can see above, I've added one more filter criteria that specify the Rating as Cold along with the existing filter for Rating as Warm. Also, I've specified the filterLogic as 1 OR 2, where 1 corresponds to the first filter and 2 corresponds to the second filter, so basically here we're saying that the account rating should either be Warm or Cold. The updated results in our lookup are shown below:

Note: By default, if no filterLogic is defined, all filter criterias are applied using the keyword AND.

Display Additional Field in our Record Picker (Lookup) Search Results

Now, it's time to display an additional field value in our record picker search result. We can display only one field from the same/related object as the additional field. For example: if we want to display the rating as well - in the search results, we can do that as follows:
import { LightningElement } from 'lwc';

export default class RecordPickerDemo extends LightningElement {

    filter = {
        criteria: [
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Warm'
            },
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Cold'
            }
        ],
        filterLogic: '1 OR 2'
    };

    displayInfo = {
        additionalFields: ['Rating']
    }

}
If you notice above, we defined one more object named displayInfo. It has a property called additionalFields which is an array with single string value i.e. the API name of our additional field to query which is Rating in our case. I can use this displayInfo object and pass it to our record picker component in the html as shown below:
<template>
    <lightning-card hide-header label="Account Record Picker Card">
        <p class="slds-var-p-horizontal_small">
            <lightning-record-picker
                label="Select Account"
                placeholder="Type Something..."
                object-api-name="Account"
                filter={filter}
                display-info={displayInfo}
            ></lightning-record-picker>
        </p>
    </lightning-card>
</template>
If you noticed above, I added another property to our lightning-record-picker named display-info and it's referring to our displayInfo object which we created in our js. Now, the search results output is also displaying the rating as shown below:


As you can see, we're only getting accounts with rating Warm or Cold.

Can we query using a different field?

By default, records are queried using the name field. However, we can use a different primary field to query records as well. We can also specify an additional field to query records. Let's say we want to query records using Rating field. The updated code for the js file is provided below:

import { LightningElement } from 'lwc';

export default class RecordPickerDemo extends LightningElement {

    filter = {
        criteria: [
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Warm'
            },
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Cold'
            }
        ],
        filterLogic: '1 OR 2'
    };

    displayInfo = {
        additionalFields: ['Rating']
    }

    matchingInfo = {
        primaryField: { fieldPath: 'Rating' }
    }
}

If you notice above, I've defined a new object named matchingInfo. In this object, we can define primaryField as well as additionalFields that we want to use to query records. The primaryField is basically an object with single property named fieldPath which should have the API name of the field you want to use. For our example, the API name is Rating for the Rating field of account. Also, the updated html is shown below:

<template>
    <lightning-card hide-header label="Account Record Picker Card">
        <p class="slds-var-p-horizontal_small">
            <lightning-record-picker
                label="Select Account"
                placeholder="Type Something..."
                object-api-name="Account"
                filter={filter}
                display-info={displayInfo}
                matching-info={matchingInfo}
            ></lightning-record-picker>
        </p>
    </lightning-card>
</template>

As you can see above, the matchingInfo property from our js is assigned to matching-info property of our lightning-record-picker.

Now, the records will be queried on the basis of Rating and not Name as shown below:


We can update our code to define an additional field to be used to query records as well. Let's see the updated code:
import { LightningElement } from 'lwc';

export default class RecordPickerDemo extends LightningElement {

    filter = {
        criteria: [
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Warm'
            },
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Cold'
            }
        ],
        filterLogic: '1 OR 2'
    };

    displayInfo = {
        additionalFields: ['Rating']
    }

    matchingInfo = {
        primaryField: { fieldPath: 'Rating' },
        additionalFields: [ { fieldPath: 'Phone' } ]
    }
}
As you can see above, we defined another property named additionalFields which is an array where we can define additional fields. We can define only one additional field here. For our use case, I used the Phone field as an additional field. Now, I can also query records using Phone field as shown below:

Making the lightning-record-picker required

We can make our lightning-record-picker required as well using the required attribute. The updated HTML code is provided below:
<template>
    <lightning-card hide-header label="Account Record Picker Card">
        <p class="slds-var-p-horizontal_small">
            <lightning-record-picker
                label="Select Account"
                placeholder="Type Something..."
                object-api-name="Account"
                filter={filter}
                display-info={displayInfo}
                matching-info={matchingInfo}
                required
            ></lightning-record-picker>
        </p>
    </lightning-card>
</template>
As you can see above, I've added the required attribute to my lightning-record-picker tag. This is a boolean attribute so we don't need to specify any value. Just adding required means, it's true. We don't need to add it if we don't want to make our field as required. Now, if we don't select a record, by clicking on the record picker, we'll get the error message as shown below:
As you can see, there is a red asterisk (*) with Select Account label as well which specifies that the field is required.

Setting a default record using record id as the component is loaded

One common use case we can encounter is to setup a default record for our lightning-record-picker as it's loaded initially. We can do that using the value attribute. Let's do some changes in our js first:
import { LightningElement } from 'lwc';

export default class RecordPickerDemo extends LightningElement {

    filter = {
        criteria: [
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Warm'
            },
            {
                fieldPath: 'Rating',
                operator: 'eq',
                value: 'Cold'
            }
        ],
        filterLogic: '1 OR 2'
    };

    displayInfo = {
        additionalFields: ['Rating']
    }

    matchingInfo = {
        primaryField: { fieldPath: 'Rating' },
        additionalFields: [ { fieldPath: 'Phone' } ]
    }

    recordId = '001H3000002jHRYIA2';
}
As you can see above, I've defined a new property in my js class named recordId. I have hardcoded it's value to the id of an account from my salesforce org. Now, I can update my HTML as well so that this account record is pre-selected in the lookup:
<template>
    <lightning-card hide-header label="Account Record Picker Card">
        <p class="slds-var-p-horizontal_small">
            <lightning-record-picker
                label="Select Account"
                placeholder="Type Something..."
                object-api-name="Account"
                filter={filter}
                display-info={displayInfo}
                matching-info={matchingInfo}
                required
                value={recordId}
            ></lightning-record-picker>
        </p>
    </lightning-card>
</template>
If you notice above, the value attribute of my record picker is assigned the recordId property which I defined in my js file. Now, as the component is loaded initially, the account record with this record id is pre-selected as shown below:

That's all for this tutorial, I hope you liked it. There are also some predefined events linked to lightning-record-picker which you can check in the official documentation here. Let me know if you need a tutorial for the same and I can create one. I will look forward to your feedback in the comments down below.


Happy Trailblazing!!

Friday, 24 February 2023

Child to Parent communication using LWC Events | LWC Tutorial | Lightning Events in LWC

Hello Trailblazers, 

I recently posted the below video on SFDC Stop YouTube Channel where we learned how can we communicate from a child lwc to a parent lwc using events.

Tutorial Video

In this post, I'm going to share the code snippet we used in the above tutorial with a brief explanation of the same. You can watch the small ~9min video, I shared above to learn the concept in detail.

Let's have a look at the code snippets now!

Child LWC

First of all, we created a child lwc. This component will fire the event on a button click, which will be handled by the parent lwc. Let's have a look at the HTML and Js code of our child lwc one by one:

child.html

<template>
    <lightning-button label="Increase Count" onclick={increaseCount}></lightning-button>
</template>
As you can see above, we defined a lightning button with label Increase Count, this button will call the js method increaseCount() which will increase the value of a counter we'll define in our js and fire an event. The parent LWC will capture the event and will display the value of this counter along with some text received in the event body.

child.js

import { LightningElement } from 'lwc';

export default class Child extends LightningElement {

    count = 0;

    increaseCount() {
        this.dispatchEvent(new CustomEvent('increasecount', {
            detail: {
                message: 'Increased count to ' + (++this.count)
            }
        }));
    }
}
As you can see above, we defined a variable count whose initial value is 0. As we click the Increase Count button, this increaseCount() will be called. It'll dispatch a new event named increasecount and in the body of this event (which is an object), we defined a property named detail. Now, in this detail property, we can pass anything, it can be a string, an array, an integer, an object...anything.

For now, in the detail of this event, we're passing an object, which has a single property named message and the value of message is: Increased count to <increased value of count variable>. This means, each time this method is called, count variable will be incremented by 1 and the string message will be passed in event detail which has the updated count. For example, when the first time, this method is called, we will have the message Increased count to 1 in the event detail. Similarly, the second time this method is called when the button is clicked again, count variable will increase again by 1 and the message: Increased count to 2 will be passed in the event detail.

Our parent lwc will accept this event and will display the message. Let's have a look at that now!

Parent LWC

Let's start by looking at the html part again:

parent.html

<template>
    <lightning-card title={message}>
        <p class="slds-var-p-around_small">
            <c-child onincreasecount={updateMessage}></c-child>
        </p>
    </lightning-card>
</template>
In this component, first of all we defined a lightning-card with title equal to the message variable that we'll define in our js. Then, for the card body, we defined a paragraph with a small padding and within that paragraph, we called our child component. Now, we know that our child lwc will fire increasecount event when the button is clicked, so we're handling the same event as: onincreasecount={updateMessage}. This means: whenever this increasecount event is fired, it'll call the updateMessage() method defined in the js of our parent lwc.

For every event which is fired by a child lwc, you can handle it by adding a prefix on before it's name and then binding it to a method defined in your js. For example: here our event name is increasecount so we added the on prefix before event name and it became: onincreasecount and we binded it to our updateMessage() method defined in our js. This updateMessage() method will receive the same event that we fired from our child component. Let's checkout the js to understand how we're handling this event.

parent.js

import { LightningElement } from 'lwc';

export default class Parent extends LightningElement {

    message = 'Updated count will appear here!';

    updateMessage(event) {
        this.message = event.detail.message;
    }
}
As you can see in the above code snippet, we defined a message variable in our js. This is the same variable which is used as the value of title in our lightning card. The default value of this variable is Updated count will appear here! so by default the lightning card will display this message as you can see in the below screenshot:


We also defined a method updateMessage(event), this method will receive the same event which is fired by our child lwc in the parameter and will update the message variable with the value that is coming from the message property of our event detail object. Remember, we defined an object in the detail property of our event body, with a single property named: message whose value was Increased count to <increased value of count variable>? So, when we do: this.message = event.detail.message; we're basically saying, get the object defined in detail property of event body (event.detail) and then get the value of message property from that object (event.detail.message). We're assigning the value of this message property from event detail object to our message variable and this message variable is displayed as the title of our lightning card.

parent.js-meta.xml

I'm going to add this component to my homepage for the demo, so I've added a target named lightning__HomePage as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>56.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Demo

Now, as we click on the Increase Count button once, the child component's counter (count variable) will increment to 1, the value of message will be Increased count to 1, the lightning card title will update and the output for the same is shown below:


Similarly, as we click on this button again, the child component's count variable will update to 2, the message passed through the event will be Increased count to 2 and the same message will be displayed in the title of our lightning card as shown below:


I'm sharing a small screen recording below so that it's clear how the component is behaving in real time:


That's all for this tutorial everyone, I hope you liked it. Let me know your feedback in the comments down below.

Happy Trailblazing!!

Tuesday, 29 December 2020

Salesforce LWC Tutorial Part 7 | Wrapping up ToDo App Project | Add Spinner | Deploy to Salesforce

 Hello Trailblazers,

Welcome to the seventh and final tutorial in LWC Tutorial Series where we're building a ToDo App Project. We're focusing on the concept of Learning By Doing in this tutorial series. In this tutorial, we're going to refine our ToDo List component by adding a spinner and some validations in LWC. We're also going to deploy our todo list component to a Salesforce Org.


So, let's continue building the above application. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

I highly recommend you to have a look at the video to understand in detail. However, let's have a quick look at the code below to understand in short:-

Apex Class (ToDoListController.cls)

As you can see above, we haven't made any change in the apex class, so the code is same as it was in the previous tutorial.

JS Snippet (todo.js)

If you see carefully, we've defined a new variable named as processing which is initially true. This variable will be used to show a spinner whenever a call to apex is performed from our lwc component. Initially, it's true because we're loading the list of tasks from Salesforce when the component is initialized. We'll now see how we need to toggle this boolean attribute in js to show/hide the spinner at multiple places and finally, we'll add a spinner component to our HTML.

If you check the addTaskToList() we have added a check first of all i.e. if our this.newTask which is our task name is blank, the method will simply return and no operation will be performed, this check will stop the user to add a blank record in our todo list. After this, we've set the processing variable to true.We've done this at the beginning, because our apex call will be asynchronous and we want our spinner to display from the moment we click on the Add button until the task is inserted in Salesforce. 

Then, we've called out insertTask method which is responsible to insert a new task in Salesforce and we've linked a finally() method as well, after the then and catch method. Inside the finally method, we again set the processing variable to false. We've done this in the finally method because we want to hide the spinner irrespective of the fact that the call to apex is successful or not, so, it doesn't matter whether we're getting a successful response or an error from apex callout, the spinner will hide as the apex call is complete.

Remember setting up the id of the new task in our insertTask method as:- this.todoTasks[this.todoTasks.length - 1].id + 1 to prevent duplicacy? I have mentioned this in the previous blog because this was important although the detailed explanation of the same is given in the video embedded above as it's also a part of enhancement.

Now, let's move on to our deleteTaskFromList(), inside this method as well, you can see that we've set the processing variable to true before we're going to perform any operation to delete the particular task, this is because we want to show the spinner before executing any code. Then, we are finding the record id of the task to delete from salesforce and finally, we're calling the deleteTask method which is used to delete the task from Salesforce by using the record id. This method is also having a finally() method attached to it after the then and catch, where we've set the processing variable to false. The reason is same, we have to hide the spinner after the apex call is complete irrespective of the fact whether the task was deleted successfully or not.

Let's have a look at getTodoTasks() method now, as you know that this is a wire method, so, it'll be called automatically when the component is initialized. Remember, we kept the initial value of processing variable as true when we initialized it? We're going to make it false now when our wire method apex call is complete. As you can see, inside our getTodoTasks() method, we're setting processing to false when the response is received from salesforce irrespective of the fact that we're getting the data or error from salesforce side when we're loading the list of tasks.

Finally, in the refreshTodoList() method, initially, we have set the processing variable to true. I have linked a finally() method to the refreshApex method as well. Inside this finally method, we've set the processing variable to false as we did in other places.

HTML Snippet (todo.html)

If you see above, inside the first lightning-layout-item tag, we've added a template with a condition which specifies, if the processing variable is true, the lightning-spinner component will be visible which is kept inside this template tag. This lightning-spinner component is responsible to display the loading spinner and is controlled by the processing variable. We've already toggled the processing variable at various places in our js code in order to show/hide the loading spinner. If you see the lightning-input tag, we've have added another property there named as autocomplete, whose value is off. This property will stop the suggestions that are coming when we're typing the name of a new task. This is also an enhancement that you can add-on to your custom lwc components.

XML Snippet (todo.js-meta.xml)

Now, it's time to deploy our lwc component to Salesforce Org. As you can see in the meta file above, we've marked isExposed property as true which will make the component visible in Salesforce Org. Apart from this, we've added a masterLabel using which you can search this component in the page builder. A friendly description of the component is added as well and under the targets tag, we've added 3 target tags:-

lightning__RecordPage:- To make our component available to a record detail page.
lightning__AppPage:- To make our component available to an app page.
lightning__HomePage:- To make our component available to a home page.

Now you can deploy this component to a Salesforce org using VSCode and you can embed your component to the homepage and test it out.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!