Lightning – ABSYZ https://absyz.com Salesforce Gold Consulting and Implementation Partner Sun, 29 Nov 2020 15:36:51 +0000 en-US hourly 1 https://absyz.com/wp-content/uploads/2020/06/cropped-favicon-1-1-32x32.png Lightning – ABSYZ https://absyz.com 32 32 Drive User Action with Floating Prompts in Lightning Experience https://absyz.com/drive-user-action-with-floating-prompts-in-lightning-experience/ https://absyz.com/drive-user-action-with-floating-prompts-in-lightning-experience/#respond Wed, 29 Apr 2020 20:42:17 +0000 http://blogs.absyz.com/?p=11202

Think of driving employees to complete compliance training, pushing them to fill out a GPTW annual survey or  sending reminders for completing Salesforce certification maintenance exams.  Salesforce Floating prompts can assist you to drive employee actions, broadcast company news, send recurring reminders & more. 

Let us look at an illustration for a Floating prompt. Below prompt is meant to drive all Project managers to complete the forecasting activity for the current month when they view their Salesforce landing page.

Image_1

Before deep diving into the creation of a Floating prompt, let us review the org-wide prompt settings.

 

Review Org-Wide Prompt Settings

Go to Setup-> In-App Guidance -> Add Prompt -> Prompt Settings.

Image_2

  1. Display between prompts: This decides the time delay between showing two prompts per app. With the current custom setting of 2 hours, you would be able to see another prompt after viewing one in the same app only after a delay of 2 hours. 
  2. Salesforce standard prompts: You would’ve come across these prompts in your org for introduction/highlighting of new Salesforce features like Recycle bin in Lightning or Controlling the density feature. These prompts are part of in-app guidance offered by Salesforce which can be activated/deactivated  from this path
  3. Custom Prompts: You can activate/deactivate all the custom prompts in your org using this option.

 

Setting up a Floating Prompt

The Authoring Bar

Let’s see the origins of the Floating prompt introduced earlier. First step would be to reach the Prompt authoring bar. You can go there from this path: “Setup-> In-App Guidance -> Add Prompt -> Open Authoring Bar”. 

Image_3

Once opened, the authoring bar would remain at the top of an App. You would be able to navigate between different pages here like you do when working within an app by switching between Home Page, record pages, list views & more. When you are on a page(see above screenshot), you would see the already added prompts to the page from 1) “Prompts on this Page” drop down. You can also add more prompts on the page you are using 2) “Add Prompt” button. 

When clicking on “Prompts on this page”,  you will be able preview & edit prompts already defined on the current page.

Add a New Prompt: Select Type & Position

From the “Add Prompt” option on the authoring bar, you will be taken to the prompt wizard. Select “Floating Prompt” from the below screen:

Image_4

Select the “Floating Prompt” option on the above screen. Next you can decide Prompt’s location. There are 6 locations where a floating prompt can be placed. Be sure you do not have important information on that part of the page as you can’t temporarily minimise the prompt without interacting with it. You can select the “Top Left” option for the current case. 

Image_5

Visibility

On the next screen, you’ll have to decide whether to restrict this prompt to certain profiles & permission set assignees or keep it open to all. In the current example, you will be allocating this to a specific profile since this message is targeted towards the Project managers group. 

Image_6

Additionally, you can add permission sets from the next screen which essentially means you can set the prompt’s visibility based on a combination of Profile & Permission sets. You can currently have a combination of upto 10 profiles & permissions on a Prompt.

Add Content

Next, comes the all important content section. 

Image_7

A floating prompt’s content consists of: 

  • Title – Header for the prompt
  • Body –  Accepts plain text only with 240 chars. The content should be concise  & convey the message effectively without any ambiguity.
  • Dismiss Button Label – Name of the Dismiss Button label
  • Action Button Label (Optional) – Name of the Action Button label
  • Action button URL (If Action button Label has values) – The “Action” button can redirect you to another URL. It does not invoke a flow or a process. For the current example, you can redirect the user to another app page where forecasting activity is done.

Scheduling

Finally, fix a date range during which you want the prompt to show up for the target audience. Since the expectation is to complete the forecasting activity by end of 1st week of May, we would keep the date range from 1st – 8th May’20

Configure the frequency at which this prompt would show.  Add the no. of times it should show & the days between each occurrence in the “Times to Show” & the “Days in Between” fields respectively. 

Image_8

The “Show prompt when the page loads” checkbox overrides the default time gap set  in “Prompt Settings” & shows the prompt every time the page loads if the user hasn’t interacted with the prompt. You can use this option to reinforce the importance of the current prompt’s message over other configured prompts.

Add remaining details & Preview

Post configuring the schedule, you can add remaining details for the prompt like Prompt Name, API name & description on the last page of the creation wizard. 

Image_9

Once done, you can Save & Preview the Prompt. 

Image_10

You can make further edits to the prompt using the “Edit” button or make it ready for use by marking it “Done”.

 

User Interaction & its impact on Floating Prompt’s Occurrences

Scenario:1 “Action” button is defined on the Floating Prompt

Image_11

Since an “Action” button is defined, the intent is for the user to complete the action. Till the action button is clicked, the Prompt would show up based on its schedule settings. 

Below are the Prompt behaviours which occur based on User Actions:

Sr. No.  User Action Prompt Behaviour
1 Do nothing, stay on the page Prompt stays
2 Do nothing on Prompt – Navigate to another page & come back to the first page where prompt is defined Show prompt when user navigates back to same page**
3 Close the prompt using ‘X’ on top right Show prompt when user navigates back to same page**
4 Click on “Do it Later” Show prompt after 1 day***
5 Click on “Forecast Now” Stop showing prompt even if more recurrences are scheduled

** Org-wide delay of 2 hrs set earlier in “Prompt Settings” is overwritten by “Show Prompt when Page loads” checkbox set in the Floating prompt’s schedule we’ve defined. If the checkbox was unchecked, the system would wait for 2 hrs from occurrence of any other prompt on the current app before showing the Floating Prompt on the current page again. 

*** Since in the Prompt’s Schedule settings “Days in between” is set to 1.

Scenario:2 “Action” button is not created on the floating prompt

With all remaining settings being  the same as in Scenario:1, Sr. No. 1-3 from the “User Action – Prompt Behaviour” mapping table in the previous scenario would still hold. Sr. No. 4’s behaviour would change to -> Stop showing prompt even if more recurrences are scheduled. This is because without the action button, the prompt only expects the user to view the message. An appropriate example can be:

Image_12

Conclusion

As mentioned in the introduction, Floating prompts are meant to drive user action. But there is another engagement activity which Salesforce prompts support – User Adoption. The other category of prompts i.e Docked prompts are primarily used for driving adoption using step by step instructions & in-prompt videos. You can expect another post on it soon 🙂 ! Meanwhile, hope you enjoyed this blog !!  Thank you for your time !!!

]]>
https://absyz.com/drive-user-action-with-floating-prompts-in-lightning-experience/feed/ 0
Summer’20 Release Treasure Hunt: Top Features https://absyz.com/summer20-release-treasure-hunt-top-features/ https://absyz.com/summer20-release-treasure-hunt-top-features/#respond Wed, 29 Apr 2020 06:04:49 +0000 http://blogs.absyz.com/?p=11168

Summer’20 is just around the corner… and with every release Salesforce introduces new features and enhancements made to the platform. Thus enhancing our productivity by using the native declarative and programmatic features.

Summer’20 official Release notes are not yet out, below are few features we have identified as few and among the coolest ones!

Let’s look at few out of the box features which are going to be introduced with this release!! 🙂

1. Flows

1.1  Before/After Handling in Flow Triggers

We recently saw Flows inherit an ability from Apex: the ability to act as a Trigger. You could select criteria which a Flow would be called automatically, and handle data.

With Summer ’20, we’re seeing yet another step in Flow becoming a fully-fledged declarative alternative to Apex: the ability to handle before and after events. This is a massive step for Flow and will grant even more power to declarative users.

Instead of being an Auto-Launched Flow, this will now be known as a ‘Record Changed’ Flow (one of a number of new Flow Types).

 

Screenshot (208)

You can choose when to trigger the flow(see image below).

FlowTrigger

1.2 Run Flows in System Mode

Now you can execute/run your flows overriding the current user’s permissions by setting your flow to run in system context with sharing. The flow still respects org-wide default settings, role hierarchies, sharing rules, manual sharing, teams, and territories, but it ignores object permissions, field-level access, or other permissions of the running user.

Flow003

1.3 Flow Loop Variables are Automatically Created

In every iteration of Flow Builder and Designer to date, we’ve had to create our loops, then create a separate loop variable resource. It’s just an extra step that felt so unnecessary.

Salesforce has addressed this by creating this resource automatically when you create a loop. Let’s say you had a loop called ‘lead_loop’, Flow Builder will automatically create a resource called ‘Current Item from lead_loop’. The result? It will save you a ton of time, and make it much easier for new Flow users to learn how to use the tool.

Flow004

1.4  Roll back Mode in Flow Debugger

With rollback mode enabled in your Flow Debugger, any changes that are executed by your Flow won’t be saved while you test it. This helps to keep your data clean and tidy while you create and test your Flows. This is one of those tiny changes that will have a huge impact.

Flow005

2. Lightning

2.1 Navigate to a record page with default values

Now, you can create  custom button or links that pass default field values to a new record using formulas.

This feature is not available for the Lightning communities, or the Salesforce mobile app.

To construct a custom button or link that launches a new record with prepopulated field values, use this sample formula:

lightning/o/Account/new?defaultFieldValues=
    Name={!URLENCODE(Account.Name)},
    OwnerId={!Account.OwnerId},
    AccountNumber={!Account.AccountNumber},
    NumberOfEmployees=35000,
RecordType=Account_Record_Type_Test,
    CustomCheckbox__c={!IF(Account.SomeCheckbox__c, true, false)}
2.2 Empty the Recycle Bin in One Step

Empty your Salesforce org’s Recycle Bin in Lightning Experience with a single click. Previously, you either selected individual items to delete, or had to switch to Salesforce Classic  to remove all items at once permanently.

224_rn_recycle_bin_admin

2.3 Split View in Standard Navigation

Standard Navigation gets a Console makeover! Console view displays multiple records and their related records on the same screen, and ‘Split View’ displays a List View within a record page:

This means that you can quickly work through records – ideal for updating overdue Tasks, all Opportunities in your pipeline, or the new Leads assigned to you…or anything you use List Views for!

SplitView
2.4 Source Tracking in Sandboxes

You can now enable Source Tracking in Developer and Developer Pro to use the Salesforce Command Line Interface (CLI) to view, pull, and push changes in the Sandbox. Once enabled, any new Sandboxes you create will have tracking enabled automatically, and after refresh for any existing Sandboxes.

3. Development

3.1 The @track decorator is no longer needed to make the Lightning Web Component Class Reactive

In order to capture changes to a field’s value and to make it reactive to changes you had to decorate it with @track before Spring’20.

But with Summer’20 @track decorators are no more needed to make the fields reactive, the fields in LWC are reactive by default now.

If a field’s value changes, and the field is used in a template or a getter of a property that’s used in a template, the component rerenders and displays the new value.

3.2 Style Lightning Web Components with Custom Aura Design Tokens

A Lightning web component’s CSS file can use a custom Aura token created in your org or installed from an unmanaged package. Tokens make it easy to ensure that your design is consistent, and even easier to update it as your design evolves.

You can define a token value once and reuse it in your Lightning component’s CSS.

Create a custom Aura token in the Developer Console by creating a Lightning Tokens bundle.

<aura:tokens>
    <aura:token name="myBackgroundColor" value="#f4f6f9"/>
</aura:tokens>

Here “myBackgroundColor” is a custom aura token.

Custom Aura tokens aren’t new, but now you can use them in a Lightning web component’s CSS file by using the standard var() CSS function. Prepend –c- to the custom Aura token.

// myLightningWebComponent.css
color: var(--c-myBackgroundColor);
3.3 Smarter Source Tracking for Lightning Web Components in Scratch Orgs

Until now, CLI commands tracked source changes for Lightning web components in a local project, but didn’t track changes to Lightning web components in a scratch org.

With Summer’20 release Salesforce command-line interface (CLI) now tracks changes to Lightning web components in a scratch org. The CLI output lists any changes, and alerts you to any conflicts between your local project and a scratch org.

This change is available in Salesforce CLI with salesforcedx v48, which released on February 15, 2020.

sfdx force:source:pullPulls 
changed source from a scratch org to your project.

sfdx force:source:pushPushes 
changed source from your project to a scratch org.

sfdx force:source:statusTracks 
changes between your project and a scratch org.

3.4  DOM API Changes May Require UI Test Updates

The content and structure of HTML, CSS, and the DOM in Lightning Experience can change at any time and can’t be considered a stable API. Automated UI tests that use tools like the Selenium WebDriver to reach into component internals require your ongoing maintenance.

4. Reports and Dashboards

With Summer’20 release now we can send the attachment while scheduling the Report/Dashboards from Salesforce Lightning.

Navigate to Report & Dashboards Setting & Enable “Let users attach reports as files to report subscription emails in Lightning Experience” Setting.

 

reports&amp;dashboards

reports&amp;dashboards002

5. Federation Id can be made case sensitive

With Summer’20 release you now have the option to make the Federation Id as case-sensitive. Previously this feature was not available.

Go to setup, from setup select single sign on settings and enable the checkbox “Make Federation Id case sensitive”.

Screenshot (214)

6. AWS Private Link

With summer’20 release Salesforce introduces the Private Connect. Assuming this will facilitate establishing connection between Salesforce and AWS VPC and other AWS Services.

AWS PrivateLink simplifies the security of data (hosted on the AWS platform) shared with cloud-based applications by eliminating the exposure of data to the public Internet. AWS PrivateLink provides private connectivity between VPCs, AWS services, and on-premises applications, securely on the Amazon network.

With AWS PrivateLink, you can connect your VPCs to AWS services and SaaS applications in a secure and scalable manner.

Screenshot (210)

From setup, go to Private Connect, choose whether you want to create an Inbound Connection/Outbound Connection.

Inbound connection will allow you to access data shared with your Salesforce Application from an AWS VPC(Virtual Private Cloud) which is an additional layer of an Amazon EC2 (Elastic Compute Cloud)Instance.

Outbound Connection will allow you to share/proxy your Salesforce Data into an AWS VPC.

Screenshot (212)

You would need to specify the end point Id of your AWS VPC and also the region in which the service is hosted.

You can also specify the option of provisioning the connections and choose whether to provision connection immediately or at a later point of time.

 

These are some of the features that we have explored out.

We will be back with Part I and Part II of the Release highlights with more information on the hot and newest features that shall roll into your Salesforce org’s with the summer’20 release.

Till then, you can sign up here for a Pre-Release Org and keep on exploring!! 🙂

]]>
https://absyz.com/summer20-release-treasure-hunt-top-features/feed/ 0
Outlook connection with Salesforce through custom Objects https://absyz.com/outlook-connection-with-salesforce-through-custom-objects/ https://absyz.com/outlook-connection-with-salesforce-through-custom-objects/#respond Wed, 19 Feb 2020 07:21:41 +0000 http://blogs.absyz.com/?p=10941

This blog post helps you to integrate Microsoft Outlook with Salesforce by using Lightning for Outlook sync by OAuth 2.0 connection method and create Custom Objects data from outlook.

Set Up Lightning for Outlook in the Microsoft Outlook

For setting up of Outlook connection to salesforce, please follow the below blog from points 1-9 to setup the users in outlook who needs to have sync with Salesforce.

.https://blogs.absyz.com/2018/07/11/step-by-step-process-of-integration-between-outlook-and-salesforce-by-service-account-connection-method/

Lightning for Outlook and Lightning Sync from Salesforce

 

  1. Enter Outlook Integration and Sync in the quick find box
  2. Enable Outlook Integration and Lightning Sync.

 

 

  • Expand the Lightning Sync section after enabling it. You could see two types of connection methods.
  • OAuth 2.0
  • Service account

Select the OAuth 2.0 and click on Log in Button.

 

Once you click on Login button, It will automatically redirect to outlook login page.

Enter the details of Global admin User of Microsoft Account and click on Accept.

 

The connection gets accepted and we will be getting the Office 365 Tenant ID automatically which is shown in below screenshot.

 

Click on Connect. The connection gets authorised and ready for testing the user connection with Outlook.

 

Enter the user’s email address whose email is same in both the systems (Salesforce & Outlook) in the Test your connection prompt.

Click on test after entering the email address. This will verify with Outlook server and enables a secure connection between both the systems.

 

Now we have successfully connected with email server, so the exchange happens between both the systems.

Define the sync settings and click on Go to Configs

 

Define lightning sync configurations.

Click on New lightning sync configurations and give the exchange behaviour as shown below.

 

 

Click on Save.

Outlook Connection Establishment:

Open your Outlook mailbox and click on mail and you can find more actions on right side.

 

Click on Get Add-ins.

 

From the search bar you can search for salesforce add in and add to outlook.

 

Once the salesforce plugin is added, login to salesforce where you can select your environment (Sandbox / Production).

 

Enter the salesforce login credentials and click on login. After successful connection we can see the standard objects displayed in the connector.

 

Now we can directly create Task, Event, Account, Contact and Lead from outlook to salesforce.

Now, we are going to learn how to add Custom Objects to this standard list.

I have used a custom Object (Agent) and some custom fields to link with Outlook.

Go to salesforce and search for global action from search bar and then create a new global action.

 

After creation of new global action (New Agent), it will take you through page layout of that action where we can add the necessary fields to that layout.

 

Enter Outlook in the search bar and click on Outlook Integration and Sync.

Expand the section of Outlook Integration and click on New Email Application Publisher Layout.

 

Create a new Layout and add the global action (New Agent) to Quick Action.

 

Now add the layout to profiles.

Click on Publisher layout assignment and add the layout to profiles.

 

 

Once this is done, we can able to view custom objects along with standard objects in Outlook.

 

create a custom object data from outlook to salesforce.

 

Limitations for creating Global action in salesforce.

 

  • Adding too many fields to an action layout can impact user efficiency. We recommend a maximum of 8 fields. To reduce the number of fields, you can set predefined values for fields that need a value but won’t often be edited. You can safely remove those fields from the layout. Set predefined values from the action detail page.

 

 

  • If we have record types for an object, we need to create global action for each record type because each record type has its own page layout.
  • Custom Objects which are on the detail side of a master-detail relationship cannot be created via Global Action. A detail object record requires a master record and can’t be created in a non-entity-specific context.
  • Ref—– https://help.salesforce.com/articleView?id=000337323&type=1&mode=1

 

]]>
https://absyz.com/outlook-connection-with-salesforce-through-custom-objects/feed/ 0
Displaying standard report data in Lightning component https://absyz.com/displaying-standard-report-data-in-lightning-component/ https://absyz.com/displaying-standard-report-data-in-lightning-component/#respond Mon, 30 Dec 2019 15:37:25 +0000 http://blogs.absyz.com/?p=10822

Sometime we might end up the slow performance of showing custom charts by querying the object data- if the data is in millions. The best way to improve the performance is by creating a standard report and getting data of report to apex with ReportManager class.
we can also pass the filter values based on your requirement and display charts in the Lightning component with the help of Javascript chartCanvas class.

 

blog-4

FYI : The above charts are constructed with standard reports- Matrix and Summary type.

 

 

 

 

 

 

 

 

 

We need to consider some standard classes.

ReportManager class helps to run a report synchronously or asynchronously.

ReportResults class contains the results of running a report.

ReportFilter class contains information about a report filter, including column, operator, and value.

and some Methods of above classes

 

describeReport(reportId) Retrieves report, report type, and extended metadata for a tabular, summary, or matrix report.

Example:Reports.ReportDescribeResult describe =  Reports.ReportManager.describeReport(reportId);

getReportMetadata() Returns metadata about the report, including grouping and summary information.

Example:Reports.ReportMetadata reportMd = describe.getReportMetadata();

getReportFilters() Returns a list of each custom filter in the report along with the field name, filter operator, and filter value.

Example: Reports.ReportFilter filterlist = reportMd.getReportFilters()[0];
filterlist .setValue(filterId);

Apex code

 

[sourcecode language=”java”]
@AuraEnabled
public static string Getreportplanned(String AccId){
Report repRec=[SELECT Id,Name,DeveloperName from Report where DeveloperName=:system.Label.CLNOV19SLS04];
string reportPlannedId=repRec.Id;
string filterId=String.valueOf(AccId).substring(0, 15);
// Retrieves report metadata
Reports.ReportDescribeResult describe = Reports.ReportManager.describeReport(reportPlannedId);
Reports.ReportMetadata reportMd = describe.getReportMetadata();
// Add/Override filters
Reports.ReportFilter filterlist = reportMd.getReportFilters()[0];
filterlist .setValue(filterId);
//and Run report
Reports.ReportResults reportResult = Reports.ReportManager.runReport(reportPlannedId,reportMd);
system.debug(‘ReportResultsJSON’+JSON.serialize(reportResult));
return JSON.serialize(reportResult);
}

[/sourcecode]

Aura component

To load chart on page load.

 

<ltng:require scripts="{!$Resource.chartjs}" afterScriptsLoaded="{!c.createPlannedchart}"/>

For displaying the report

 

 <canvas id="chartCanvas" height="300" width="300"></canvas>

To view standard report

[sourcecode language=”java”]
View Report
[/sourcecode]


Js Code

[sourcecode language=”java”]
var urlPlannedreport = ‘/lightning/r/Report/’+getPlannedReportId+’/view?queryScope=userFolders&fv0=’+accIdsub;

createPlannedchart: function(component) {
var chartCanvas = component.find(“plannedChart”).getElement();
var action = component.get(“c.getreportplanned”);

action.setParams({
“AccId”: component.get(“v.accrecId”)
});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === “SUCCESS”) {
var reportResultData = JSON.parse(response.getReturnValue());
// alert(JSON.stringify(reportResultData));
var chartData = [];
var chartLabels = [];
var nullcheck = reportResultData.groupingsDown.groupings;
if (nullcheck !== null) {
for (var i = 0; i < (reportResultData.groupingsDown.groupings.length); i++) {
//Iterate and prepare the list of Labels for the chart
var labelItem = reportResultData.groupingsDown.groupings[i].label;
chartLabels.push(labelItem);
var keyTemp = reportResultData.groupingsDown.groupings[i].key;
//Prepeare the chart data to be plotted.
var valueTemp = reportResultData.factMap[keyTemp + “!T”].aggregates[0].value;
chartData.push(valueTemp);
}
}
//Construct chart-doughnut/bar
var chart = new Chart(chartCanvas, {
type: ‘bar’,
data: {
labels: chartLabels,
datasets: [{
label: “Count”,
data: chartData,
backgroundColor: [
“#52BE80”,
“#76D7C4”,
“#1E8449”,
“#2ECC71”,
“#FFB74D”,
“#E67E22”,
“#F8C471”,
“#3498DB”,
“#00BCD4”,
“#D32F2F”,
“#82E0AA”,
“#AFB42B”
]
}]
},
options: {
responsive: true,
title: {
display: true,
text: ‘Planned Visits’
},
scales: {

yAxes: [{
ticks: {
// max: 100,
stepSize: 25,
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: ‘Visits Count’
},
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: ‘Created Date’
}
}]
},
maintainAspectRatio: false,
legend: {
display: false,
position: “right”,
fullWidth: false,
}
}
});

} else(state === “ERROR”) {
console.log(‘Problem, response state: ‘ + state);
}

});
$A.enqueueAction(action);
}
[/sourcecode]

You can change the look of charts with the help of chartcanvas methods.

 

 

 

]]>
https://absyz.com/displaying-standard-report-data-in-lightning-component/feed/ 0
Using Modal/ Popup in Lightning Web Components https://absyz.com/using-modal-popup-in-lightning-web-components/ https://absyz.com/using-modal-popup-in-lightning-web-components/#comments Thu, 31 Oct 2019 07:31:54 +0000 http://blogs.absyz.com/?p=10469

In this blog, we will be learning to use Modal/ Popup in Lightning Web Component. We will be using SLDS classes that helps in showing or hiding the Modal.

The below classes help in showing and hiding of the modal

 

  1. slds-fade-in-open – Shows the modal
  2. slds-backdrop_open – Shows the backdrop(greyed out)

So, adding and removing these classes at an action will show/ hide the modal accordingly.

In this example, we will be making a Modal component and show the data required by checking the sObject of the current record page it is being used. So, this component can be used at any sObject record page, and the required server call can be performed.

Let’s have a look at the components.

 

Apex Class

Modal_LWC_controller.cls
This class checks the sObject type and calls the function required for that sObject

 

/**
* @File Name          : Modal_LWC_controller.cls
* @Description        : 
* @Author             : Abhishek Kumar
* @Group              : 
* @Last Modified By   : abhishek.kumar@absyz.com
* @Modification Log   : 
* Ver       Date            Author      		    Modification
* 1.0    19/10/2019   	Abhishek Kumar     				1.0
**/
public with sharing class Modal_LWC_controller {
    
    @AuraEnabled(cacheable=true)
    public static WrapperClass fetchWrapperData(Id sObjectId){
        WrapperClass wrapperClassVar = new WrapperClass();
        if(sObjectId.getSobjectType() == Schema.Account.SObjectType){
            wrapperClassVar.contactList = Modal_LWC_controller.getRelatedContacts(sObjectId);
        }else if(sObjectId.getSobjectType() == Schema.Contact.SObjectType){
            wrapperClassVar.accId = Modal_LWC_controller.getAccId(sObjectId);
        }
        System.debug('wrapperClassVar-->>'+wrapperClassVar);
        return wrapperClassVar;
    }
    
    public static List<Contact> getRelatedContacts(String accId){
        return [SELECT Id, Name, Phone, Email FROM Contact WHERE AccountId =:accId];
    }
        
    public static String getAccId(String contactId) {
        return [SELECT Id, AccountId FROM Contact WHERE Id=:contactId].AccountId; 
    }
    
    public class WrapperClass {
        @AuraEnabled
        public List<Contact> contactList {get; set;}
        @AuraEnabled
        public Id accId{get; set;}
        
        public wrapperClass() {
            this.contactList = new List<Contact>();
        }
    }
}

 

LWC Components

modal_LWC.html

 

<!--
  @File Name          : modal_LWC.html
  @Description        : 
  @Author             : Abhishek Kumar
  @Group              : 
  @Last Modified By   : abhishek.kumar@absyz.com
  @Modification Log   : 
  Ver       Date            Author      		    Modification
  1.0    19/10/2019     Abhishek Kumar                  1.0
-->
<template>
    <lightning-button variant="brand" label={btnLabel} title={btnLabel} onclick={openModal} class="slds-m-left_x-small"></lightning-button>
    <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class={modalClass}>
    <div class="slds-modal__container">
        <header class="slds-modal__header">
        <h2 id="modal-heading-01" class="slds-modal__title slds-hyphenate">{modalHeader}</h2>
        </header>
        <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
            <template if:true={isContact}>
                <lightning-record-view-form
                    record-id={accountId}
                    object-api-name="Account">
                    <div class="slds-grid">
                        <div class="slds-col slds-size_1-of-2">
                            <lightning-output-field field-name="Name"></lightning-output-field>
                            <lightning-output-field field-name="Website"></lightning-output-field>
                        </div>
                        <div class="slds-col slds-size_1-of-2">
                            <lightning-output-field field-name="Potential_Value__c"></lightning-output-field>
                            <lightning-output-field field-name="Most_Recent_Closed_Date__c"></lightning-output-field>
                        </div>
                    </div>
                </lightning-record-view-form>
            </template>
            <template if:false={isContact}>
                <div class="slds-border_left slds-border_right slds-border_top">                    
                    <lightning-datatable
                        key-field="id"
                        data={contactList}
                        show-row-number-column
                        row-number-offset={rowOffset}
                        hide-checkbox-column
                        resize-column-disabled
                        columns={columns}>
                    </lightning-datatable>
                </div>
            </template>
        </div>
        <footer class="slds-modal__footer">
        <button class="slds-button slds-button_neutral" onclick={closeModal}>Cancel</button>
        <button class="slds-button slds-button_brand" disabled>Save</button>
        </footer>
    </div>
    </section>
    <div class={modalBackdropClass}></div>
    
    </template>

modal_LWC.js

 

import { LightningElement, track, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent'
import fetchWrapperData from '@salesforce/apex/Modal_LWC_controller.fetchWrapperData';

const columns = [
  { label: 'Name', fieldName: 'Name' },
  { label: 'Email', fieldName: 'Email', type: 'email' },
  { label: 'Phone', fieldName: 'Phone', type: 'phone' }
];

export default class Modal_LWC extends LightningElement {
  @track columns = columns;   
  @track accountId; 
  @track contactList;
  @track rowOffset = 0;
  @track error;   
  @track btnLabel = '';   
  @track modalHeader = '';
  @track isContact = false;
  @track modalClass = 'slds-modal ';
  @track modalBackdropClass = 'slds-backdrop ';
  @api recordId;  //Stores recordId
  @api objectApiName;   //Stores the current object API Name

  connectedCallback() {   //doInit() function, Dynamically changing the modal header and button label as per sObject, and also assigning the isContact property as per sObject
    if(this.objectApiName === 'Account'){
      this.isContact = false;
      this.modalHeader = 'Related Contacts';
      this.btnLabel = 'See Related Contacts';
    }else if(this.objectApiName === 'Contact'){
      this.isContact = true;
      this.modalHeader = 'Account Details';
      this.btnLabel = 'See Account Details';
    }
  }

  //Adds the classes that shows the Modal and does server calls to show the required data
  openModal() {
    this.modalClass = 'slds-modal slds-fade-in-open';
    this.modalBackdropClass = 'slds-backdrop slds-backdrop_open';
    fetchWrapperData({sObjectId: this.recordId})
      .then(result => {    //Returns the wrapper 
        if(result.accId != null){
          this.accountId = result.accId;
          this.isContact = true;
        }else{
          this.contactList = result.contactList;
          this.isContact = false;
        }
      })
      .catch(error => {
        const event = new ShowToastEvent({
          title: 'Error Occured',
          message: 'Error: '+error.body.message,
          variant: 'error'
         });
        this.dispatchEvent(event);    //To show an error Taost if error occurred while the APEX call
        });
  }

  //Removes the classes that hides the Modal
  closeModal() {
    this.modalClass = 'slds-modal ';
    this.modalBackdropClass = 'slds-backdrop ';
  }
}

Alternatively, we can use <template if:false> for showing/ hiding the modal without changing the classes.

So as mentioned in the above components, this component is being used on Account and Contact record pages. Let us see how it looks on both of them.

Account Record Page:

On clicking the button, ‘See Related Contacts’, it queries the contacts under the account and displays that.

 

Contact Record Page:

On clicking the button, ‘See Account Details’, it fetches the related Account details and displays the fields mentioned.

 

 

Clicking the ‘Cancel’ button, closes the Modal/ Popup.
Similarly, this component can be used to show required data in the Modal as per the sObject using this on the record page.

 

]]>
https://absyz.com/using-modal-popup-in-lightning-web-components/feed/ 1
LWC with Aura Components,Calling controller from LWC,LDS in LWC https://absyz.com/lwc-with-aura-componentscalling-controller-from-lwclds-in-lwc/ https://absyz.com/lwc-with-aura-componentscalling-controller-from-lwclds-in-lwc/#respond Fri, 27 Sep 2019 09:41:17 +0000 http://blogs.absyz.com/?p=10188

Calling controller from LWC:

Lightning web components can import methods from Apex classes into the JavaScript classes using ES6 import.Once after importing the apex class method you can able to call the apex methods as functions into the component by calling either via the wire service or imperatively.

https://videopress.com/v/gAkX46zD?preloadContent=metadata

Import Syntax

import apexMethod from’@salesforce/apex/Namespace.Classname.apexMethod’;

apexMethod : This identifies the Apex method name.

Classname : The Apex class name.

Namespace : The namespace of the Salesforce organization

To expose an Apex method to a Lightning web component, the method must be static and either global or public. Annotate the method with @AuraEnabled

[sourcecode language=”java”]

public with sharing class ContactAuraService {

    public ContactAuraService() {

    }

    @AuraEnabled(cacheable=true)

    public static List<sObject> getContactList(){

        String query = ‘select id,Name,Email,Phone From Contact’;

        return database.query(query);

    }

}

[/sourcecode]

After importing the apex class method you can able to call the apex methods as functions into the component by calling either via the wire service or imperatively. We have three ways to call Apex method

1.Wire a property

2.Wire a function

3.Call a method imperatively.

1.Wire a property:

<!–LWCWireExample.html–>

[sourcecode language=”java”]

<template>

    <lightning-card title=”Wire a property” icon-name=”standard:contact”>

            <div class=”slds-m-around_medium”>

                <template if:true={contacts.data}>

                    <template for:each={contacts.data} for:item=”con”>

                        <p key={con.Id}>{con.Name}</p>

                    </template>

                </template>

            </div>

        </lightning-card>

</template>

[/sourcecode]

<!–LWCWireExample.js–>

[sourcecode language=”java”]

import { LightningElement, wire } from ‘lwc’;

import getContactList from ‘@salesforce/apex/ContactAuraService.getContactList’;

 

export default class LWCWireExample extends LightningElement {

    @wire(getContactList) contacts;

}

[/sourcecode]

<!–LWCWireExample.js-meta.xml–>

[sourcecode language=”java”]

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata” fqn=”LWCWireExample”>

    <apiVersion>45.0</apiVersion>

    <isExposed>true</isExposed>

    <masterLabel>Wire a property For Contact List</masterLabel>

     <targets>

    <target>lightning__AppPage</target>

    <target>lightning__RecordPage</target>

  </targets>

</LightningComponentBundle>

[/sourcecode]

2.Wire a function:

This mechanism is needed if you want to pre-process the data before going to the Lightning App.

<!–LWCWireExample.js–>

[sourcecode language=”java”]

import { LightningElement, wire,track } from ‘lwc’;

import getContactList from ‘@salesforce/apex/ContactAuraService.getContactList’;

export default class LWCWireExample extends LightningElement {

    @track contacts;

    @track error;

    @wire(getContactList)

    wiredContacts({ error, data }) {

        if (data) {

            this.contacts = data;

        } else if (error) {

            this.error = error;

        }

    }

}

[/sourcecode]

<!–LWCWireExample.html–>

[sourcecode language=”java”]

<template>

    <lightning-card title=”Wire To a function Example” icon-name=”standard:contact”>

         <div class=”slds-m-around_medium”>

            <template if:true={contacts}>

                <template for:each={contacts} for:item=”con”>

                    <p key={con.Id}> {con.Name} </p>

                </template>

            </template>

            <template if:true={error}>

                {error}

            </template>                

        </div>

    </lightning-card>

</template>

[/sourcecode]

<!–LWCWireExample.js-meta.xml→

[sourcecode language=”java”]

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata” fqn=”LWCWireExample”>

    <apiVersion>45.0</apiVersion>

    <isExposed>true</isExposed>

    <masterLabel>Wire to a function For Contact List</masterLabel>

     <targets>

    <target>lightning__AppPage</target>

    <target>lightning__RecordPage</target>

  </targets>

</LightningComponentBundle>

[/sourcecode]

3.Call a method imperatively:

If an Apex method is not annotated with cacheable=true, you must call it imperatively.

<!–LWCWireExample.js→

[sourcecode language=”java”]

import { LightningElement, wire,track } from ‘lwc’;

import getContactList from ‘@salesforce/apex/ContactAuraService.getContactList’;

export default class LWCWireExample extends LightningElement {

    @track contacts;

    @track error;

handleLoad() {

getContactList()

.then(result => { 

this.contacts = result;

this.error = undefined;

})

.catch(error => {

this.error = error;

            this.contacts = undefined;

});

}

}

[/sourcecode]

<!–LWCWireExample.html–>

[sourcecode language=”java”]

<template>

     <lightning-card title=”Call a method imperatively Example” icon-name=”standard:contact”>

         <div class=”slds-m-around_medium”>

<p class=”slds-m-bottom_small”>

                <lightning-button label=”Get Contacts” onclick={handleLoad}></lightning-button>

            </p>

            <template if:true={contacts}>

                <template for:each={contacts} for:item=”con”>

                    <p key={con.Id}> {con.Name} </p>

                </template>

            </template>

            <template if:true={error}>

                {error}

            </template>                

        </div>

    </lightning-card>

</template>

[/sourcecode]

<!–LWCWireExample.js-meta.xml–>

[sourcecode language=”java”]

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata” fqn=”LWCWireExample”>

    <apiVersion>45.0</apiVersion>

    <isExposed>true</isExposed>

    <masterLabel>Call a method imperatively</masterLabel>

     <targets>

    <target>lightning__AppPage</target>

    <target>lightning__RecordPage</target>

  </targets>

</LightningComponentBundle>[/sourcecode]

Lightning Web Components with Aura Components:

In an Aura component, to refer to either Aura components or Lightning web components, use camel case with a colon separating the namespace and the component name.Aura components can contain Lightning web components.However, the opposite doesn’t apply.Lightning web components can’t contain Aura components.

https://videopress.com/v/zQF9hWqg?preloadContent=metadata

<!–ContactList.cmp→

[sourcecode language=”java”]

<aura:component>

    <lightning:card title=”Aura component” iconName=”custom:custom14″ />

    <c:lWCWireExample/>

</aura:component>

[/sourcecode]

<!–TestApp.app–>

[sourcecode language=”java”]

<aura:application extends=”force:slds”>

    <c:ContactList/>

</aura:application>[/sourcecode]

LDS in Lightning Web Component:

LDS is the Lightning Components counterpart to the Visualforce standard controller, providing access to the data displayed on a page. For Lightning components, Salesforce added a new Feature – Lightning Data Service (LDS) in its Winter ’17 release. We can use LDS in our Lightning components to perform CRUD operations like create,read,update a record without use of any Apex code.Now we see how to implement LDS in LWC.

Create Record through LDS :

First import the createRecord method from ‘lightning/uiRecordApi’ in client side controller.

https://videopress.com/v/B3l43t5o?preloadContent=metadata

Syntax:

import { createRecord } from ‘lightning/uiRecordApi’;

<!–accountMangerLds.html–>

[sourcecode language=”java”]

<template>   

 <lightning-card title=”Account Manager”>

        <lightning-layout>

                <lightning-layout-item size=”6″ padding=”around-small”>

<lightning-card title=”Create Account”>

<lightning-input label=”Id” disabled value={accountId}></lightning-input>

<lightning-input name=”Account Name”    label=”Account Name” type=”text” onchange= {accountNameHandler}></lightning-input>

<lightning-input name=”Account Phone”   label=”Account Phone” type=”phone” onchange= {accountPhoneHandler}></lightning-input>

<lightning-button label=”Create Account” variant=”brand” onclick= {createAccount}></lightning-button>

                       </lightning-card>

                 </lightning-layout-item>

          <lightning-layout-item size=”6″ padding=”around-small”>

     </lightning-layout-item>

   </lightning-layout>

</lightning-card>

</template>

[/sourcecode]

<!–accountMangerLds.js–>

[sourcecode language=”java”]

import { LightningElement, api } from ‘lwc’;

import { createRecord } from ‘lightning/uiRecordApi’;

export default class AccountManagerLDS extends LightningElement {

    @api accountName;

    @api accountPhone;

    @api accountId;

    accountNameHandler(event){

        this.accountId = undefined;

        this.accountName = event.target.value;

    }

    accountPhoneHandler(event){

        this.accountId = undefined;

        this.accountPhone = event.target.value;

    }

    createAccount(){

        const fields = {‘Name’ : this.accountName,’Phone’ : this.accountPhone};

        const recordInput = {apiName:’Account’,fields};

        createRecord(recordInput)

           .then(response=>{

            this.accountId = response.id;

           })

           .catch(()=>{

           

           });

    }

}[/sourcecode]

<!–accountMangerLds.js-meta.xm–>

[sourcecode language=”java”]

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata” fqn=”accountManagerLDS”>

    <apiVersion>45.0</apiVersion>

    <isExposed>true</isExposed>

    <masterLabel>Create Record LDS</masterLabel>

     <targets>

    <target>lightning__AppPage</target>

    <target>lightning__RecordPage</target>

  </targets>

</LightningComponentBundle>[/sourcecode]

]]>
https://absyz.com/lwc-with-aura-componentscalling-controller-from-lwclds-in-lwc/feed/ 0
Top Highlights of Salesforce Winter’20 Release: Part II https://absyz.com/top-highlights-of-salesforce-winter20-release-part-ii/ https://absyz.com/top-highlights-of-salesforce-winter20-release-part-ii/#respond Tue, 03 Sep 2019 06:49:01 +0000 http://blogs.absyz.com/?p=10358

Hello Ohana!! We are back with the highlights of the winter’20 release. Let’s see what are the new features Salesforce is rolling out in order to make the platform more efficient and make our work easy!! 🙂 Let’s get started…

Development:

1.Lightning web components open source:

The Lightning Web Components framework is now open source, empowering you to explore the source code, customize the framework to your needs, and build enterprise-ready web components on any platform, not just Salesforce.

The benefits are significant. You can now learn one framework instead of several. You can share code between apps. And you’re using a cutting-edge framework built on web standards and based on the latest patterns and best practices.

You can also develop on LWC off-platform: see here.

2.  Add Lightning Web Components as Tabs:

This change applies to Lightning web components in Lightning Experience and all versions of the Salesforce app.

In order to add a lightning web component in a custom tab, define the <lightning_tab> in the <component>.js-meta.xml configuration file .

Screen Shot 2019-08-30 at 12.03.11 PM.pngCreate a custom tab for this component and add it to your App Launcher.

3. Communicate Across Salesforce UI Technologies with Lightning Message Service :

You can now use the Lightning Message Service API to communicate across the DOM, between Aura components, Visualforce pages, and Lightning web components.

In Lightning Experience, you often have multiple components on a page. Previously, if you wanted a Visualforce page to communicate with a Lightning web component in Lightning Experience, you needed to implement a custom publish-subscribe solution. Now, you can use the Lightning Message Service API to handle that communication.

4. Launch into Lightning Experience Apps with the Mobile App Launcher:

The App Launcher has landed on mobile. You can switch between all your favorite Lightning apps, just like in Lightning Experience desktop.

This change applies to the new Salesforce mobile app for iOS and Android in all editions, except Database.com.

This change is generally available to users with the New Salesforce Mobile App user permission.

Previously, to use all the cool features that are available in Lightning apps, you needed to be on a desktop computer. Now you can access Lightning apps from anywhere.

mobile_app_launcher_desktop_compare

5. Navigate Users directly to an App:

Develop Lightning web components and Aura components that navigate users to a specific page in an app.

Now you can create components that link directly to your app and to a specific page in your app.

Use the lightning-navigation Lightning web component or the lightning:navigation Aura component with the new standard__app page reference type.

Lightning Flows:

1.Start a Flow on a Schedule:

Now you can schedule an autolaunched flow to start on a particular date and time and set the frequency to once, daily, or weekly. If you want that scheduled flow to run only for a set of records, you can specify an object and filter.

To start a flow for a set of records, select the filter conditions in the Start element. When your flow starts, a flow interview runs for each record that matches your filter—no looping required. The matching record is stored in the $Record global variable, so you can reference the variable or its fields throughout your flow.

222_rn_forcecom_flow_fbuilder_start_editstartmodal

To check whether a scheduled flow exceeds the org limit, check the debug logs to see the number of records that the flow runs on. The number of records equals the number of scheduled flow executions, because a flow runs for each record. Track the number of records with the new FLOW_START_SCHEDULED_RECORDS debug log line. If the flow exceeds the org limit, Salesforce sends an error email to either the admin who last modified the associated flow or the Apex exception email recipients.

222_rn_forcecom_flow_fbuilder_start_elementoncanvas

Fig: On the Flow Builder canvas, a flow shows its scheduled start time.

Salesforce CLI: New and Changed Commands:

1. Discover New and Changed CLI Commands:

New Parameters have been added in the Salesforcedx pre-release version 47.

Screen Shot 2019-08-30 at 12.42.41 PM

Query in Bulk API 2.0 :

Bulk API 2.0 now supports bulk query jobs. These jobs enable asynchronous processing of SOQL queries and are designed to handle queries that return large amounts of data (10,000 records or more).

The Bulk API 2.0 implementation has several advantages:

  • It does not require you to handle batches. All results are returned in one set.
  • Limits have been simplified and are available to clients via a /limits endpoint.
  • This implementation is better integrated with other Salesforce REST APIs:
    • It does not require a special X-SFDC-Session header.
    • It supports all the regular OAuth workflows.
    • Its design is more consistent with the other Salesforce APIs.

Protect Your Salesforce App with Enhanced Mobile Security:

Previously, customers with high security and compliance needs had to rely on external mobile device management (MDM) solutions to use the app.

But now with winter’20 release Mobile application management (MAM) has come to the new Salesforce mobile app. Secure your app with the convenient, highly customizable protection of enhanced Mobile Security.

Mobile Security keeps Salesforce app data safe and users’ personal data personal. You can control a range of policies to create a security solution tailored to your org’s needs. You can limit user access based on operating system versions, app versions, and device and network security. You can also specify the severity of a violation.

Screen Shot 2019-08-30 at 1.07.35 PM

Generally Available Updates:

1. Make Your List Views Stay on Topic with Topic Filters:

Keep your list views #organized by adding filters based on topics. You can add filters for up to two topics per list view.

2. Save Ink and Paper with Printable View for Lists:

You don’t have to print your entire screen just to make a hard copy of your list. Generate a condensed, minimalist, ink-saving view of your lists and related lists with Printable View.

Just select Printable View from a list.

rn_lists_printable_view_before

The columns and fields shown on the printable view reflect your page layout or related list preferences.

rn_lists_printable_view_after

3. Complete Tasks in a Single Click:

Now sales reps can mark tasks complete from table view. This means reps can spend more time getting things done and less time crossing them off their list.

To update a task’s status, select Mark Complete.

222_sales_productivity_tasks_mark_complete

4. Find Email File Attachments in One Click:

Now it’s easy to send files as an email attachment. When reps choose files to attach to an email, they can use the new Related Files link. Click the link to show all the files that are part of the record. This feature applies to all activity-enabled objects, such as leads, contacts, person accounts, opportunities, cases, and custom objects.

When selecting a file to attach to an email, click Related Files. Select the files to attach, and then click Add.

rn_sales_productivity_email_related_files

5. Scan and Scroll the Activity Timeline:

Improvements to the activity timeline make scanning, finding, and acting on activities easier for your sales reps. Infinite scrolling eliminates clicks and eases scanning for the activity that a rep is looking for.

No more Load More Activities button. Grouping activities in the activity timeline by month lets reps find activities quickly and make sense of periods of time without customer activity. Relative dates, for example, one, two, or three months ago, let reps see the pace of activities.

rn_sales_productivity_activity_timeline_UI

6. Track Setup Changes Made to Connected App Policies and Settings:

The Setup Audit Trail now tracks some connected app policy and setting updates. For example, if your org has multiple admins, you can see who updated a connected app’s callback URL or access permissions.

rn_security_setup_audit_trail_capps

These were few of the release highlights from the Winter’20 release. For a full fledge list of updates do refer the Winter’20 release notes.

That’s all for now…

Stay Updated and keep on Trailblazing!!

]]>
https://absyz.com/top-highlights-of-salesforce-winter20-release-part-ii/feed/ 0
Field Service Lightning https://absyz.com/field-service-lightning/ https://absyz.com/field-service-lightning/#comments Thu, 04 Jul 2019 06:50:35 +0000 http://blogs.absyz.com/?p=9986

Salesforce has expanded their Service Cloud offerings by adding Field Service Lightning. Field Service Lightning works with Service Cloud, adding functionality for dispatching, monitoring, and reporting field service representative’s activity. Salesforce FSL product focuses on putting the right mobile employee in the right place, at the right time, to meet or exceed customers’ expectations. The offline-friendly “Field Service Lightning” mobile app for iOS and Android makes work a pleasure for technicians in the field. App users can update work orders, track parts, gather customer signatures, and connect with dispatchers from their mobile devices.

With Field Service Lightning, you get the tools that you need to manage work orders, schedule appointments and manage your mobile workforce.

Here are some of the things we can do with Field Service Lightning are:

  1. Create Service Technicians, Dispatchers and Agents and add details about them.
  2. Set up service territories where the technicians need to work.
  3. Manage Locations, Inventory and customer sites.
  4. Schedule work orders for customers based on the customer preference and required skills.
  5. Create Maintenance Plans.
  6. Dispatch Supervisors the ability to view and manage work from either Gantt chart or map view.
  7. Generate Service Reports.
  8. Captures electronic signatures for work orders or service reports.
  9. App users can update work orders and close the work orders.

Components of Field Service Lightning:

1.Core Features.

2.Managed Package.

3.Field Service Mobile App.

After enabled Field Service Lightning the Core Features are ready for configuring. Through Managed Package we can gain access to the dispatcher console, scheduling tools, a range of custom objects. The Field Service Mobile App works offline, so technicians can complete their work even with limited or no network connectivity.

Setup and Working of Field Service Lightning:

Field Service Players (Users) fall into the following categories:

1) FSL Admin.

2) FSL Agent.

3) FSL Dispatcher.

4) FSL Technician (Resource).

The FSL Admin configures Field Service Lightning and assign required permissions to various users. The FSL Agent handles cases and creates work orders and books appointments with customer. The FSL Dispatcher assigns technicians to the work orders and appointments and schedule appointments based on skills and routing policy. The FSL Technician (Resource) receive work orders and appointments and also update the status of their appointments and closes them in the Field Service mobile app.

1)FSL Admin:

Admin will do all configuration settings like enable Field Service Lightning, Install the Field Service Lightning Managed Package and sets up user permission sets to different users as needed for our org.

Enable & Installing Field Service Lightning:

  1. From Setup, enter Field Service Settings in the Quick Find box, then select Field Service Settings.
  2. Enable Field Service Lightning and click Save.

After Field Service Lightning is enabled, install the Field Service Lightning managed package to gain access to the dispatcher console, scheduling tools, a range of custom objects.

Once the package is installed, the App Launcher includes two new apps.

1

  • The Field Service app is for dispatchers. The Field Service tab in this app leads to the dispatcher console.
  • The Field Service Admin app is for administrators. The Field Service Settings tab in this app leads to the managed package settings.

Admin will work on Field Service Admin App. Admin will do all configuration settings through Field Service Settings tab in Field Service Admin App. Admin has to create permission sets from Permission Sets Tab then he can assign different permission sets to different users.

2

Below table is for needed permission sets for Different Users.

FSL Admin FSL Admin License

FSL Admin Permissions

FSL Agent FSL Agent License

FSL Agent Permissions

FSL Dispatcher FSL Dispatcher License

FSL Dispatcher Permissions

FSL Resource FSL Mobile License

FSL Scheduling License

FSL Resource Permissions

Setting up FSL:

First admin has to create Operating hours with Time slots from Operating Hours Tab. Operating Hours will define a Working hours for the Service resource.

Admin has to create Service Territories with Operating Hours from Service Territories Tab. Then he should give Service territory members in Service Territory Member related list. Service territories will define a regions where service resource will work.

Admin has to create Service Resource with Resource type from Service Resources Tab. Every resource should tag with one User. Admin should define skills to the resource through Resource Views section in the Service Resource Detail page.

Admin has to create Work Types with Duration Type, Estimated Duration and Due date from Work Types Tab. Work Type will define the which type of work it is. If he selected Auto-Create Service Appointment check box it will automatically creates Service Appointment when creating work order.Admin should define skills to the work type through Skills Editor section.

Admin has to create Scheduling Policies and Work Rules through Respective Tabs. Scheduling Policies will filter out service resources based on Work Rules when dispatcher scheduling Service Appointments. Admin should define Work rules to Scheduling policies through “Scheduling Policies work rule” related list in Scheduling policies.

2)FSL Agent:

Agent will work on “Field Service App”. Agent has to create Work Orders and Service Appointments. He can create Work Orders and Service Appointments from Respective Tabs.

16

If there is any emergency appointment, agent can directly Schedule Service Appointments through Book Appointments, Candidates, Emergency actions in Feed tab.Through Emergency action he can schedule service appointment to nearest available  service resource regardless of territory.

17

Agent can add Products, Product line items through Related lists in Work Order. These products will be used to complete the work order. Agent can also attach Knowledge Articles through Knowledge section related list.

3)Dispatcher:

Dispatcher will work on Dispatcher Console. He can open Dispatcher console through Field Service Tab in Field Service App. It will display Service Appointments left side of the Dispatcher console. We can fileter service Appointments By selecting List views.

Horizon date will filter all service appointments before the Horizon date. Policies will filter the service resources when scheduling appointments. It will assign appointment to resource based on scheduling policies.

21

Dispatcher can schedule Service Appointments in two ways. One is selecting the service appointment and then click on schedule button and another one is just dragging and dropping the service appoint to resource. If he scheduled service appointment the scheduled start and scheduled end date will automatically update based on Duration Type, Estimated Duration, Due Date which admin has mentioned in work type.

If he Dispatched the Service appointment by clicking on Dispatch button the service appointment will share with the service resource.

Coming to Gantt chart which is right side of the Dispatcher console. In GANTT it will display the Territories and resources under territories and it will display scheduled appointments in resource slots. And we can filter resources by using filter icon.

Coming to MAP tab in GANTT chart it will display all resources, service appointments, service territories markers.

27

It will display markers based on selecting options from markers tab in MapLayers. Dispatcher can search service resources and display marker by selecting service resource tab. Dispatcher can draw a polygon for particular area, through that he can mass update the appointments in that polygon. Dispatcher can see live traffic by selecting Traffic.

4)FSL Technician (Resource):

Technician can work in Field Service Lightning mobile app. He can see scheduled appointments in his mobile app. Technician can get driving directions through Get Driving Directions option and he can contact customer. He can start working on scheduled appointments. Technician can add consumed products through Consumed products Related list on Work Order.

Technician can generate service report and he can take digital signature from customer and he can send that Service Report to Customer.

Technician can complete the Service Appointment by updating status.

38

Conclusion:

Finally, Field Service Lightning is important tool for many industries like vending machine services,  public utilities and transportation, telecommunications, waste management, in-home health and child care, financial services, retail, professional services, and manufacturing.

 

]]>
https://absyz.com/field-service-lightning/feed/ 1
Lightning Testing Service https://absyz.com/lightning-testing-service/ https://absyz.com/lightning-testing-service/#respond Fri, 28 Jun 2019 09:40:04 +0000 http://blogs.absyz.com/?p=9945

As the size of complexity of Lightning Apps grew bigger, we could try to maintain the code quality of our Lightning Component like the same way we maintain in Apex. So the first thing we must start to look at was, what Salesforce provides out of the box for us to gauge the quality, the sad thing is we have “Apex testing frameworks” for testing code coverage of Apex, but there is nothing for lightning right now. So obviously the next thing for us to look at was what tools available outside Salesforce, that developers are already using right now.

Luckily there are lot of tools already available with other Client testing frameworks. Couple of libraries like Jasmine, Mocha are available but the problem is these libraries don’t exactly work out of Lightning Component because lightning works on Aura framework.

What is Lightning Testing Service?

Lightning Testing Service(LTS) is “Managed Package” developed and released by Salesforce which provides wrapper for us to integrated existing client frameworks to be used with lightning component.

What is Wrapper?

LTS doesn’t aim to reinvent the wheel and provide us with a whole new way of testing Javascript. All LTS aims to do is to provide the resource for us to be able to use what developers are already using as  “Industry standards” that salesforce provides.

Some Key features:

  • LTS is supported with Jasmine and Mocha which are the two most popular client side testing frameworks today.

  • LTS is able to be used with Salesforce DX and as well as in non Salesforce DX context.

Now Lets see End – to – End flow of how we can use Lightning Component Service:

  1. Create your Lightning Component.
  2. Install LTS.
  3. Write a Javascript test suite.
  4. Create a Test Runner app.
  5. Run your Tests.

Create your Lightning Component

  1. In the Developer Console, click File > New > Lightning Component. Specify QuickContacts as the bundle name and click Submit
  2. Implement the component as follows:

<aura:component implements=”force:appHostable”>

<p>ContactList goes here</p>

</aura:component>

3. The component implements the force:appHostable interface to indicate that it can run in the Salesforce1 applicationLightning components can include other Lightning components and regular HTML marku

4. Click File > Save to save the file

Install Lightning Testing Service

Its time to Install LTS into our Org. LTS can be used with Salesforce DX context and as well as non Salesforce DX context. Testing Lightning component with LTS and testing apex is quite similar.There are two ways you can install the LTS. The simplest is to use the Salesforce DX CLI. If you’re not using Salesforce DX, you can manually install the unmanaged package.

Write your tests using a JavaScript testing framework of your choice. We provide easy-to-use wrappers for Jasmine and Mocha.

A simple Jasmine test spec looks like the following:

/*** This is a ‘hello world’ Jasmine test spec*/

describe(“A simple passing test”, function() {

    it(“checks that true is always true”, function() {

        expect(true).toBe(true);

    });

});

A similar Mocha test looks, well, similar:

/*** This is a ‘hello world’ Mocha test */

var assert = require(‘assert’);

describe(‘Test the nature of truth’, function() {

    describe(‘A simple passing test’, function() {

        it(‘checks that true is always true’, function() {

            assert.equal(true, true);

        });

    });

});

You can write your own wrapper if you prefer a different testing framework. It’s not hard, but plan on half a day to a day of work.

The LTS also provides utilities specific to the Lightning Component framework, which let you test behavior specific to Aura components. Your test suite is deployed in the form of an archive (zip) static resource. Once the LTS is installed and configured, you make changes to your test suite, create the archive, and upload it to your org. Once uploaded you can run the test suite via the command line or via URL.

1.If your using LTS with Salesforce DX

Salesforce DX includes a one line command for automatically installing the LTS unmanaged package. Once installed, you can work with your test suite in a variety of ways from the command line. This approach also facilitates systematic automated testing.The Salesforce DX CLI also allows you to use the sfdx command line tool to perform automated testing as part of your development process, including automated process, such as continuous integration.

  • For installing Salesforce DX CLI follow the instructions given below for your operating system :
  • Install the Salesforce DX CLI in the Salesforce DX Setup Guide
  • Verify that the Salesforce DX CLI plug-in is installed and updated by running the following command in your shell or terminal application:

→ sfdx update

Additional verification details are available in Verify Your Installation and Install the Plug-In in the Salesforce DX Setup Guide.

  • Install the LTS package with the following command:

          → sfdx force:lightning:test:install

This installs the latest version of the LTS package into your default SFDX org. See the        help for the install command for additional options.

After you install LTS with Salesforce DX, you can run your tests from the command line using the sfdx tool. For example:

→ sfdx force:auth:web:login -s     # connect to your scratch org

→ sfdx force:source:push           # push local source to the scratch org

→ sfdx force:lightning:test:run -a jasmineTests.app   # run the test suite

When you run the

→ force:lightning:test:run -a jasmineTests.app

command in a connected workspace you should see something like the following:

This tells you that the command line tools are working, and connected to your development org.

      2. If your not using Salesforce DX

If you’re not using Salesforce DX, you’re missing out a lot, but you can still use LTS.      Installing the LTS package is just like installing any other unmanaged package.

  • Log in to your org. We recommend that you create a new DE org for evaluating the LTS.
  • Go to the project Releases page, and click the package installation URL for the latest release.
  • Authenticate again with the credentials for your DE org.
  • Follow the normal package installation prompts. We recommend installing the package for admins only.

          However you install it, the LTS package includes the following items:

Example test suites

  • Jasmine JavaScript files in archive static resources
  • Mocha JavaScript files in archive static resources
  • Example components to be tested
    • Components, an Apex class, and a custom label
  • LTS infrastructure
    • Jasmine framework and wrapper
    • Mocha framework and wrapper
    • LTS test utilities
    • Test runner component
    • Wrapper test app

Once installed, you can run the example test suite by going to the following URL in your org:

→  https://<myServer>/c/jasmineTests.app (Jasmine)

→ https://<myServer>/c/mochaTests.app (Mocha)

This page tells you that the package is correctly installed and LTS is working in your org.

Write a Javascript test suite
Components for Testing

The components provided in the package can be accessed as you would any Aura component.

  • In the Developer Console
  • In the Force.com IDE, in the /aura/ directory
  • By converting your org’s metadata into a format that you can work with locally, using Salesforce DX

You can also explore the components directly from the repo. They’re available in the lightning-component-tests/main/default/aura directory.

There are more than a dozen different components, designed to be used in illustrative tests. Each of the components has a description of its behavior in its “.auradoc” documentation file.

Test Suites

The example tests are included in the form of static resources. There are four test suites included in the LTS package, three for Jasmine and one for Mocha:

  • jasmineHelloWorldTests.resource — A very simple Jasmine example including one passing and one failing test.
  • jasmineExampleTests.resource — The main Jasmine example test suite.
  • jasmineLightningDataServiceTests.resource — Some Jasmine examples specific to testing Lightning Data Service-based components.
  • mochaExampleTests.resource — The Mocha example test suite, which provides examples parallel to the main Jasmine test suite.

The remainder of the static resources are infrastructure used by the LTS. They’re briefly described in Use Another JavaScript Test Framework.The jasmineExampleTests.resource and mochaExampleTests.resource files are each a single JavaScript file containing a complete test suite. It’s a single file for convenience in delivery and exploration. Your own test suites can include many such files. The test suites are copiously commented. The code and comments serve as the official documentation for how to write tests.

Run Your Tests

And the final step is to run our tests,

  1. If your not using DX, we just have to push that to whatever source we want and navigate to actual Aura application and it will run all our tests in a nice UI.
  2. If your using DX its even simpler because we can utilize our CLI command

→ sfdx fore:lightning:test:run

In order to get all the coverage.

Benefits:

  • It increase the code quality which helps to build Customer Trust.
  • It helps in catching problems at the very early stage of development which in turn helps in saving time and money.

Points to Remember:

  • Don’t run tests in your production org. The LTS doesn’t provide an isolated test context or transaction wrapper. DML operations you perform in your tests won’t be rolled back at the end of the test. We recommend that you run your LTS test suites only in scratch orgs, using data provided by the test suite itself.
  • Second thing is LTS does not provide any kind of Code Coverage and Matrics.

 

]]>
https://absyz.com/lightning-testing-service/feed/ 0
Usage of Spring ’19 component — lightning:unsavedChanges https://absyz.com/usage-of-spring-19-component-lightningunsavedchanges/ https://absyz.com/usage-of-spring-19-component-lightningunsavedchanges/#comments Tue, 05 Mar 2019 09:04:25 +0000 http://blogs.absyz.com/?p=9737

Accidents are commonplace! And yeah, Spring  ’19 has come up with a new component lightning:unsavedChanges. Voila!!

We often come across situations where we type in data and then we accidentally refreshes, closes the page or press back button and all the entered data is lost!!  lightning:unsavedChanges  comes in to help here! It notifies the user about the unsaved changes in the page during the above mentioned situations and provides them the choice to continue, discard or save the data and handles the process accordingly. No more frustrations over data loss!!

Before we move ahead, it would be handy to remember that this component requires API version 45.0 or later and is not supported by one.app

In this blog, we demonstrate a sample of how this component works.

[sourcecode language=”java”]
<aura:component controller=”unsavedChangesClass” implements=”force:appHostable, flexipage:availableForAllPageTypes, flexipage:availableForRecordHome, force:hasRecordId, forceCommunity:availableForAllPageTypes, force:lightningQuickAction” access=”global” >
<lightning:unsavedChanges aura:id=”unsavedData”
onsave=”{!c.handleSave}”
ondiscard=”{!c.handleDiscard}”/>
<aura:attribute name=”contactDetail” type=”Contact” default=”{‘sobjectType’ : ‘Contact’}”/>

<lightning:card title=”Create Related Contact”>
<lightning:input aura:id=”firstName” label=”FirstName” value=”{!v.contactDetail.firstName}” onchange=”{!c.handleDataChange}”/><br/>
<lightning:input aura:id=”lastName” label=”LastName” required=”true” value=”{!v.contactDetail.LastName}” onchange=”{!c.handleDataChange}”/><br/>
<lightning:input aura:id=”phone” label=”Phone” value=”{!v.contactDetail.Phone}” onchange=”{!c.handleDataChange}”/><br/>
<lightning:button variant=”brand” label=”Create Contact” onclick=”{!c.saveContact}”/>
</lightning:card>
</aura:component>
[/sourcecode]

CONTROLLER

[sourcecode language=”java”]

({
//Method call on Create Button Click
saveContact : function(component, event, helper){
helper.createContact(component, event);
},

/*This method sets the boolean for unsavedChanges to true,
* so that it indicates the containment that unsaved data is rpesent
* */
handleDataChange: function(component, event, helper) {
var unsavedData = component.find(‘unsavedData’);
unsavedData.setUnsavedChanges(true, {label: ‘creating related contact?’});
},

/**
* This method will be called when user click save button from dialog window
* Save your unsaved changes here
* */
handleSave: function(component, event, helper) {
helper.createContact(component, event);
},

/**
* This method will be called when user clicks ‘discard changes’ button from dialog window
* */
handleDiscard: function(component, event, helper) {
var unsavedData = component.find(‘unsavedData’);
unsavedData.setUnsavedChanges(false);
}
})
[/sourcecode]

HELPER

[sourcecode language=”java”]
({
createContact : function(component, event){
var action = component.get(‘c.createContact’);
action.setParams({‘accId’ : component.get(‘v.recordId’),
‘lName’ : component.find(‘lastName’).get(‘v.value’)});
action.setCallback(this, function(response){
var state = response.getState();
if(state === ‘SUCCESS’){
var unsavedData = component.find(‘unsavedData’);
unsavedData.setUnsavedChanges(false);

var navEvt = $A.get(“e.force:navigateToSObject”); //To navigate
navEvt.setParams({
“recordId”: response.getReturnValue().Id,
});
navEvt.fire();
}else{
console.log(‘error’);
}
});
$A.enqueueAction(action);
}
})
[/sourcecode]

APEX

[sourcecode language=”java”]
public with sharing class unsavedChangesClass {
@AuraEnabled
public static Contact createContact(Id accId, String lName){
Contact con = new Contact(lastname=lName,
accountId = accId);
insert con;
return con;
}
}
[/sourcecode]

The process is majorly handled by the function setUnsavedChanges within the lightning component.  This method holds two arguments  –

  • A Boolean argument to indicate if usaved data is present in the page or not. (True if unsaved content is present, false otherwise)
  • An optional object argument.

Upon data entry, we set the setUnsavedChanges to true; And therefore, when the user takes any action that loses data, it notifies the containment that unsaved data is present in the page and the dialogue window pops up as shown in the screenshot. Now, depending on the user’s decision, the handleSave  or handleDiscard custom methods will be invoked. The onsave attribute controls the action to  handle saving unsaved content  and the  ondiscard attribute  controls the action to handle discarding unsaved content. Also, keep in mind that, these methods should call the setUnsavedChanges() method again to return control back to the Lightning UI.

[wpvideo 8Z6jekSz]

]]>
https://absyz.com/usage-of-spring-19-component-lightningunsavedchanges/feed/ 3