Thursday 20 October 2022

ChartJs - Scatter Chart Points/Dots On click Functionality

SCENARIO


While working on one of the requirements for an Automobile sector projector for a client based out of Dallas, Texas. There was a requirement to open the record page dynamically in a new tab when clicking on scatter chart points/dots in the VF page using Chartjs.

CHALLENGE


Although we can use standard apex:chart tags for representing charts, we had to use ChartJs for this requirement. So we used ChartJs functionality for building custom logic to open multiple record pages in a new tab when clicked on data points.

APPROACH


We have used the apex controller for fetching data dynamically and displaying it using VF Page. Here, the Amount & Month field of the Account Standard object is used, where the Month field will represent the data of X-Axis & Amount field will represent the data of Y-Axis respectively. Below is an example.

EXAMPLE


In this example, we have created an apex controller named 'ChartDataExample'
where we fetch data for plotting the chart and displaying it on VF Page 'ScatterChart'.

Step1:Create an Apex Controller.
Step2:Create a VF Page.

OUTPUT



CONCLUSION


By following the above-mentioned code, we can open the record page dynamically in a new tab when clicking on points/dots in the scatter chart on VF Page.

If you have any questions you can reach out our Salesforce Consulting team here.

Thursday 15 September 2022

Dynamic Scatter chart in Vf page using ChartJs


SCENARIO


While working on one of the requirements for an Automobile sector project for a client based out of Dallas, Texas, There was a requirement to display dynamic data responsively into a Scatter chart using the VF page. 

CHALLENGE


The “Standard Report Chart” component can be used to display the chart on the page but we have several custom logic and filter to be implemented in a VF page then the Standard Report Chart” has filter Restrictions. To prevent that problem, we have used ChartJs.
 

APPROACH


We have used the VF page and apex controller to display dynamic data for the Account standard object. We have taken the Number of Quantities as the X axis and the Amount as the Y axis for plotting the data dynamically in this scatter chart using chartJs.

Below is an example of a scatter chart.

Example:-

In the example, we have drawn a scatter chart to display the Account amount field and No of quantity field data.

Step 1:- Create an Apex controller with the name 'ChartVfController'.

Retrieving Account data and setting on the VF page.

Step 2:- Create a VF page with the name 'ChartVf'.

VF page consists of a canvas tag, and the ChartJs library uses that canvas to draw the chart.

The most important thing is chart configuration, all the chart behavior is based on the config that we set to the chart. Below are main three attributes.
  • type:- It defines the type of chart being rendered, here we have 'scatter'. 
  • data:- Here we pass the chartLabels and chartData and other settings for the scatter chart.
  • options:- Additional settings for chart.  

Output:-



If you have any questions you can reach out our Salesforce Consulting team here.

Thursday 8 September 2022

Notify Case Creator when something is posted/commented on Chatter using Salesforce Flow

SCENARIO


While working on one of the requirements for an Electric Automotive Company based in Sweden, there was a requirement to send an Email to the Case creator when something is posted or commented on chatter.

APPROACH


As the requirement is pretty straightforward, The client wants to send an email to the case creator. We have many ways to achieve this requirement like Apex Code, but Salesforce encourages us to code less.

So, we have used Record Trigger Flow to fulfill this requirement.

Below are the steps to achieve the requirement:

Step 1:-  Define flow properties.

  • Click Setup.
  • In the Quick Find box, type Flows.
  • Select Flows then click on the New Flow.
  • Select the Record-Triggered Flow option and click on Next and configure the flow as follows:
    • How do you want to start building: Freeform

Step 2:- Select Object and Set Entry Condition. 

Give Input as follows:
  • Object: Feed Item.
  • Trigger the Flow When: A record is created or updated.
  • Condition Requirements: All Conditions Are Met(AND).
  • Field: ParentId.
  • Operator: Starts With.
  • Value:500(Case Object record Id starts with "500...").
  • When to Run the Flow for Updated Records: Every time a record is updated and meets the condition requirements.
  • Optimize the Flow for Actions and Related Records. 


Step 3:- Get Case Records. 

Drag Get Record Element into canvas from Data Section under Elements Tab from the ToolBox & Give Input as follows:
  • Object: Case.
  • Condition Requirements: All Conditions Are Met(AND).
  • Field: Id.
  • Operator: Equals.
  • Value:{!$Record.Parent:Case.Id}.
  • How Many Records to Store: Only the first record.
  • How to Store Record Data: Automatically store all fields.
  • Join start Element to Get Element.



Step 4:- Create a Decision. 

Drag Decision Element into canvas from Logic Section under Elements Tab from the ToolBox & Give Input as follows:
  • Condition Requirements to Execute Outcome: All Conditions Are Met(AND).
  • Resource: {!Get_Case_Records.CreatedBy.Id}.
  • Operator: Is Null.
  • ValueFalse.
  • When to Execute Outcome: If the condition requirements are met.
  • Join Get Element to Decision Element.

Step 5:- Define Body and Subject Variables for Email.

We need to create flow variables for the Body & Subject portion of the email.
Click New Resource under Elements Tab from the ToolBox & Give Input as follows:
  • Resource Type: Text Template.
  • API Name: TextTemplate.(Write as per your convenience)
  • Body: Comment has been Made. (Write as per your convenience)
  • Click Done.
Repeat the same above steps for Subject.
  • Resource Type: Text Template.
  • API Name: SubjectTemplate.(Write as per your convenience)
  • Body: Hi How are you?. (Write as per your convenience)
  • Click Done.

Step 6:- Send an Email. 

Drag Action Element into canvas from Interaction Section under Elements Tab from the ToolBox, scroll down the list from the left-hand side and select Email from the bottom, in the Action select Send Email & Give Input as follows:
  • Set Body & Subject variables in their respective input field.
  • Press the Don't Include Button for RecipientEmailAddresses(comma-separated) and set it to Include(True).
  • RecipientEmailAddresses(comma-separated):{!Get_Case_Records.CreatedBy.Email}.
  • Click Done.
  • Join Decision Element to Email Action Element for Case Creator.


Step 7:- Now Save the flow & then Activate it.

FLOW DIAGRAM




CONCLUSION


By following the steps mentioned above you can send an Email Notification to Case Creator when something is Posted/Commented on the Chatter.

If you have any questions you can reach out our Salesforce Consulting team here.

Thursday 1 September 2022

How to use ChartJS to generate a chart in a lightning web component?

The age of Data Science nowadays places a lot of importance on data visualization. Visual representation of the data puts more impact on the user interface. But the issue is to build custom, responsive, reactive charts and graphs in salesforce. Open source is one of the best sources for this kind of solution. The ChartJs is an open source solution that powers, to create charts and graphs that are completely responsive, accessible, and reactive, giving the best performance. By using ChartJs in salesforce, we can create custom charts and graphs.

In this blog, We will see how we can leverage the power of ChartJs to build a responsive Bar chart in LWC. We will see how to pull information from an Opportunity and feed it into the bar chart.

Why use ChartJS?

The charts can be added to the pages using the App Builder’s “Standard Report Chart” component. However, the report filters can be used to display relevant data on the charts but when we have a lot of custom logic and filters to be implemented in a lightning component then the “Standard Report Chart” have filter limitations. ChartJs is a handy solution for this. Let's jump for example.

Example:-

In the example we will draw a bar chart for latest 10 Opportunity amounts whose stage is Closed won.

Step 1:- Download ChartJs library.
  • Click Here to open link and right click on page and save as.
  • Upload file in Static Resource with the name 'ChartJS'.

Step 2:-
 Create a LWC with the name 'chart'.
HTML consist a canvas tag, the Chartjs library uses that canvas to draw the chart.
  
Here we have declared two @api attributes in the chart component
  • loaderVariant - Used to set the loader variant from the parent component.
  • chartConfig - Used to pass the chart settings and data from the parent component, so that we can reuse this component for different charts.


Step 3:- Create an apex class to get Opportunity data.
Retrieving Opportunity data.

Step 4:- Create  parent LWC named 'barChartExample'.
Calling child component chat and set chart configration.

The wire method gets the opportunity data and feeds it into the chart lwc.

The most important thing is chartConfiguration, all the chart behaviour is based on the config that we set to the chart. Below are main three attributes.
  • type:- It defines the type of chart being rendered, here we have 'bar'. 
  • data:- Here we pass the chartLabels and chartData and other settings for the bar chart.
  • options:- Additional settings for chart.


Output:-



If you have any questions you can reach out our Salesforce Consulting team here.

Thursday 11 August 2022

Support special characters when opening document from Salesforce to SharePoint using Rest API

SCENARIO

While working on one of the requirements for a Manufacture sector project for a client based out of Atlanta, GA, there was a requirement to allow special characters like % & # _ ( ) * - . in the document name while uploading from salesforce to SharePoint and open the document from salesforce custom LWC component.

Let's brief on the scenario: To store\manage files client is using SharePoint through integration. While users upload documents in the salesforce, files are uploaded to SharePoint and shown to salesforce custom component. Now the client has requested new enhancement to allow special characters as well like % & # _ ( ) * - in document name.

Document upload with special characters works fine as we were using salesforce content document to upload files. After that our custom API is responsible to upload same file and give response back to open uploaded files on success dialog box.

However, file was being uploaded in SharePoint and few changes were done in Custom API to provide response back for the document name containing special character.

CHALLENGE

Custom API changes were not enough to make solution fully work as we were able to open such documents from success dialog box but not from salesforce Custom Component. We were using SharePoint OOTB REST API to build link for SharePoint document link.

APPROACH

We have used salesforce APEX ENCODINGUTIL class to encode file name in URL. This solved the issue for most of the documents having special characters but not for which contains space in Document name.

After few analysis, we found ENCODINGUTIL replace space with '+' sign. With the tricky solution we resolved the issue by replacing '+'  with '%20' in encoded Document name. Let's understand with the example.

EXAMPLE:

  • Find below few specific parameter being used in solution.
    • Document Name : Test % & # _ ( ) * - .docx
    • OOTB\Standard SharePoint document Encoded URL : 
      SiteURL/Shared%20Documents/General/Test%20%25%20&%20%23%20_%20(%20)%20%20-%20.docx
  • To get document details, we make SharePoint  REST API callout.
  • In the response, we get FileRef As 
    SiteURL/Shared Documents/Genetal/Test % & # _ ( ) * - .docx
  • As we can see from both the URL SharePoint document URL is Encoded and in the response FileRef is not Encoded in format.
  • So we need to Encode FileRef  and replace '+' with '%20' in the apex as below.
String DocumentencodedUrl = EncodingUtil.urlEncode(FileRef, 'UTF-8');
//By using EncodingUtil class and its methods we can encode and decode URL strings.

System.Debug('Encoded Document URL--> '+DocumentencodedUrl);
// Encoded Document URL--> SiteURL%2FShared+Documents%2FGenetal%2FTest+%25+%26+%23+_+%28+%29+*+-+.docx

String DocumentUrl = DocumentencodedUrl.replace('+','%20');
//By replace string function we are replacing '+' with '%20'

System.Debug('Document URL--> '+DocumentUrl);
//Document URL--> SiteURL%2FShared%20Documents%2FGenetal%2FTest%20%25%20%26%20%23%20_%20%28%20%29%20*%20-%20.docx

In the above code, we have used EncodeUtil class and its urlEncode Method to encode the URL string and replace the method to replace '+' with '%20'.

  • Now our DocumentencodedUrl will work and document can be opened from salesforce custom component.


CONCLUSION

By encoding URL and replacing '+' with '%20' we can resolve the document URL issue having special character and space.

 
If you have any questions you can reach out our
Salesforce Consulting team here.

Thursday 4 August 2022

Create Notifications with LightningAlert, LightningConfirm, and LightningPrompt Modules


The Web Hypertext Application Technology Working Group (WHATWG) updated the HTML specification in early 2021 to remove support for the alert(), confirm(), and prompt() native APIs when used in a third-party context. So, Browsers like Chrome and Safari are now planning to end support for cross-origin use of the window.alert(), window.confirm(), and window.prompt() native APIs.

To address this issue in any LWC or Aura component, Salesforce has introduced LightningAlert, LightningConfirm, and LightningPrompt in the Summer'22 release. See Summer'22 release notes Click here.

So now to generate notifications from your Lightning web components, use the new modules LightningAlert, LightningConfirm, and LightningPrompt instead of native APIs.

The below examples show how to use LightningAlert, LightningConfirm, and LightningPrompt in Lightning web components.



Example

Let's look at the example, There are 3 buttons in LWC to display the notification Alert, Confirm and Prompt. 

Below is a code and output for LightningAlert, LightningConfirm, and LightningPrompt notifications.


In this example, a modal with a header, message, and two buttons are created. If the user enters text and clicks "OK" in the prompt, the .open() function returns a promise that resolves to the input value; however, if the user clicks “Cancel,” the promise resolves to null. 


Output





If you have any questions you can reach out to our Salesforce Consulting team here.

Thursday 28 July 2022

Fill the form and display data into data table without storing it into sObject/database using LWC

SCENARIO


While working on one of the requirements for an Automobile sector project for a client based out of Dallas, Texas, there was a requirement to add data using a form in LWC and display it into the dataTable without storing it into sObject/database.

CHALLENGE


Although the requirement seems easy, we faced challenges while displaying records into the dataTable and reRendering it when a new record is added.
 

APPROACH


To display records without storing them into sObject/database, We used a JSON object that will be responsible to store all the data to be displayed in the dataTable.
Also, we declared that JSON object as a reactive property using the @track decorator. So the table can be reRendered automatically when the value of that variable is changed/updated.

Data.html

<template>
    <lightning-card title="Add data into Datatable">
        <lightning-layout>
            <lightning-input class="slds-p-around_medium" label="Make"  type="string" name="Make"  onchange={makeChangedHandler} required="true"> </lightning-input>
            <lightning-input class="slds-p-around_medium" label="Model" type="string" name="Model" onchange={modelChangedHandler} required="true"> </lightning-input>
            <lightning-input class="slds-p-around_medium" label="Year" type="date" name="Year" onchange={yearChangedHandler} required="true"> </lightning-input>
        </lightning-layout>
        <lightning-button class="slds-m-left_x-small" label="Display" variant="brand" onclick={handleClick}>
        </lightning-button>
        <lightning-datatable key-field="id" id="datatable" data={fields} columns={columns}>
        </lightning-datatable>                 
    </lightning-card>  
</template>

Data.js

import { LightningElement,track } from 'lwc';

export default class Data extends LightningElement {
     columns = [{
        label: 'Make',
        fieldName: 'Make',
        type: 'text',
        sortable: true
    },
    {
        label: 'Model',
        fieldName: 'Model',
        type: 'text',
        sortable: true
    },
    {
        label: 'Year',
        fieldName: 'Year',
        type: 'Date',
        sortable: true
    },
];

    strMake;
    strModel;
    strYear;
    @track fields =[];
    
    makeChangedHandler(event){
        this.strMake = event.target.value;  
    }
    modelChangedHandler(event){
        this.strModel = event.target.value;
    }
    yearChangedHandler(event){
        this.strYear = event.target.value;
    }

    handleClick(){
        if(this.strMake  &&  this.strModel  && this.strYear)
        {
            this.fields = [...this.fields,{'Make' : this.strMake, 'Model' : this.strModel, 'Year' : this.strYear}];   
        }
        this.strMake ='';
        this.strModel ='';
        this.strYear ='';
        //code to clear field once values are entered
        this.template.querySelectorAll('lightning-input').forEach(element => {
        element.value = null;     
        });
    }
}

There are 3 input fields in the form. Whenever the values will be entered in these fields, it will get stored in their respective variables (strMake, strModel, strYear).

On click of Display button, these 3 inputs will be validated and pushed into an array, which is then used to display data in the data table. Also, it will clear these 3 input fields and allow users to enter another record.

As the array is declared as a reactive property, it will reRender the table automatically to display the newly created record.



OUTPUT




CONCLUSION


By using the above-mentioned approach & code, We will be able to add data into the data table without using sObject or saving data into a database in LWC.

If you have any questions you can reach out to our Salesforce Consulting team here.