June 28, 2018

How to get current datetime as per the logged in user timezone in apex?

Returns the current Datetime based on a GMT calendar. So, system.now() and Datetime.now() returns Datetime based  on a GMT calendar.

Returns the current Datetime based on the user timezone settings in the user detail.

Sample code:

system.debug('System DateTime is ' + DateTime.now());

system.debug('System DateTime is ' + System.now());

system.debug('User DateTime is ' + DateTime.now().format());

system.debug('User DateTime is ' + System.now().format());


June 27, 2018

How to find duplicate Accounts in Lightning Experience?

1. Open Account Record.

2. Select Related. If duplicate Accounts are found, you will see View Duplicates button to merge it.

Salesforce Help article - https://help.salesforce.com/articleView?id=account_merge_lex.htm&type=5

June 26, 2018

Limitations in Similar Opportunities in Salesforce

1. Use the Similar Opportunities related list on the opportunity’s detail page to find Closed/Won opportunities with common information.

2. The criteria used to find similar opportunities is determined by your administrator. The search finds a maximum of 10,000 opportunities with close dates in a three-month period and displays up to 300 of the records that best match the search criteria. The results are ranked by the number of matching fields.

3. Results can be filtered by Close date or by matching fields.

4. To see how a record in the search results is similar to your current deal, hover over the opportunity name. The matching fields are highlighted in the Match Criteria sidebar.

For implementing it, check the below link


June 25, 2018

Sample Action in Einstein Bot

Sample code:

Apex Class:

public with sharing class ChatBotUtil {

    public class ChatBotCertInput {
        public String cert;

    public class ChatBotCertOutput {
        public String certName;
        public String certCode;
    @InvocableMethod(label='Get Cert Name and code' description='Returns the Cert Name and Code')
    public static List < ChatBotCertOutput > getCertList(List < ChatBotCertInput > listInputs) {
        List < ChatBotCertOutput > results = new List < ChatBotCertOutput >();
        for ( ChatBotCertInput cert : listInputs ) {
            ChatBotCertOutput item = new ChatBotCertOutput();
            if ( cert.cert == 'ADM' ) {
                item.certName = 'Salesforce Administrator';
                item.certCode = 'ADM 201';
            } else if ( cert.cert == 'Platform Developer I' ) {
                item.certName = 'Salesforce Platform Developer I';
                item.certCode = 'PD1';
            } else if ( cert.cert == 'Platform Developer II' ) {
                item.certName = 'Salesforce Platform Developer II';
                item.certCode = 'PD2';
        return results;

Einstein Builder:

June 24, 2018

What happens if 24 hour Platform Event limit is hit?

Platform event limits apply to a 24-hour cycle. Before delivering new events, such as a change in order status, to subscribed clients, Salesforce checks your allocation and how many events have been used in your Salesforce org in the last 24 hours. If the number of events used is lower than the 24-hour allocation, Salesforce delivers events to subscribers. If you did hit your allocation for events in the previous 24 hours, Salesforce doesn’t deliver new events. But, they’re queued within a brief time window until event allocation is available.
If the user has multiple browser tabs using empApi, the streaming connection is shared and is counted as one client for that user. A client that exceeds the concurrent client allocation receives an error and can't subscribe. When one of the clients disconnects and a connection is available, the new client can subscribe

June 22, 2018

How to find original Chatter post and original date of post in Salesforce?

1. Go to Report Types.

2. Create a Custom Report type with Feed Revisions as the primary object.

3. Go to Reports tab.

4. Click New report. Select Feed Revisions report type.

Feed Revisions Report in Salesforce

June 20, 2018

Einstein Bot in Salesforce

Einstein Bot greets your customers, answers their questions, and it can even dip into your fulfillment system and retrieve the customer's order status. In case the customer does need attention from an actual agent, the bot can smoothly transfer the customer to an available agent, and serve coffee while they are waiting.

Einstein Agent chatbots, built natively on the Salesforce Platform, will allow any company to deliver automatic service at scale using Einstein AI technology.

Using Einstein Chatbot builder, you can easily set it up.

To setup, follow the steps in below link
Check the below 2 minutes video

Dialogs are conversation snippets that control what your bot can do.

Intents are the customer's reasons for interacting with your bot.

An entity represents a type of data that you want to collect from a customer.
Text, DateTime, Date, Money, Number, Person, Location, Organization, Percent, Boolean,
and Object (standard Salesforce or custom)

A variable is a container that stores a specific piece of data collected from the customer or output from Salesforce.
The following types are available for custom variables.

Add a Bot Profile
Expand a bot’s capabilities and give it access to features like Field Service Lightning by assigning it a custom profile.
Each bot has a Basic Chatbot User profile, but you can create a custom profile and add it to a bot.

Send an outgoing message from your bot to your customer.
A message can be static text or dynamic text from merge fields.
The merge fields reference objects and fields that are currently stored in your bot variables.
The merge field syntax is: {$API_VariableName} or {$API_VariableName.Field}.
Merge context and system variables into bot messages with merge syntax.

Gather information from your customer.

Run an autolaunched flow, send email, or use Apex to read, update, or delete Salesforce objects, retrieve data
and display it to the customer, and retrieve external data from a third-party API.

Specify the conditions that start any of the following actions: call a dialog from within the current dialog,
redirect to a different dialog, clear a variable value, transfer to an agent, and set variables.

Transfer Bot Conversations
1. Use the Transfer to Agent System Dialog to Transfer Conversations.
Transfer conversations to an agent in the queue attached to the Chat deployment defined on the Transfer to Agent dialog.
2. Use the Dialog Rule Element to Transfer Conversations.
a. Transfer Bot Conversations to a Queue
You can route bot conversations to a queue of agents by using the Rule Action Dialog Step.
And, you can help customers who initiates a transfer when agents are offline with the No Available Agents dialog .
b. Transfer Bot Conversations to Another Bot
Create custom solutions in your org by adopting a multi-bot strategy.
Use the Dialog Rule Element to transfer bot conversations to another bot.

How to Setup Einstein Bot in Salesforce?

1. Go to Einstein Bots under Service Cloud Einstein.

2. Enable Einstein Bots.

3. Accept the terms and conditions.

4. Click "Try Einstein" button.

5. Select Edit action in Live Agent in Deployment Channels section.

6. Enable Live Agent Channel and nable Einstein Bots Options Menu. Click Save button.

7. Click New in My Bot.

8. Click Next.

9. Give Einstein Bot Name and Description. Click Next.

10. Enter Einstein Bot Greeting Message. Click Next.

11. Enter Einstein Bot Menus. Click Create.

12. Click Finish Button.

13. Select Dialogs.

14. Select New Dialog.

15. Give Name and description and Save.

16. Select Question.

17. Enter question and click New Slot.

18. Click Add Choice.

19. Add multiple choices.

20. Select Next Step and Save.

21. Click Activate button to activate it.

Calling Apex method from another Apex method callback in Salesforce Lightning

Sample Code:

Lightning Component:

<aura:component implements="force:appHostable"

    <div class="slds-box slds-theme_default">
<lightning:button variant="brand" label="Click" onclick="{!c.call1}"/>        


Lightning Component Controller:

call1 : function(component, event, helper) {
var action = component.get("c.firstMethod");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                if ( response.getReturnValue() === 'error' ) {
    call2 : function(component, event, helper) {
        var action = component.get("c.secondMethod");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {


Apex Class:

public class Sample {

    public static String firstMethod() {
        return 'error';
    public static String secondMethod() {
        return 'Success';



June 19, 2018

What is the difference between @RestResource and @InvocableMethod?

RestResource Annotation 
The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource. @RestResource is at the class level. It is used to expose a class as rest source.

Example - http://www.infallibletechie.com/2017/08/simple-inbound-rest-api-using-apex-in.html

InvocableMethod Annotation 
Use the InvocableMethod annotation to identify methods that can be run as invocable actions. Invocable methods are called with the REST API and used to invoke a single Apex method. Invocable methods have dynamic input and output values and support describe calls. @Invocable Method is used at the method level. these are called with REST API and it is used to invoke a single method.

Example - http://www.infallibletechie.com/2016/08/invocable-method-in-salesforce.html

How to enable/disable component caching in Salesforce?

To enable/disable component caching in Salesforce

1. Go to Session Settings.

2. Check Enable secure and persistent browser caching to improve performance.

For better performance, Enable secure and persistent browser caching to improve performance should be enabled in Production and disabled in Sandbox.

June 14, 2018

Object not found in Target Object in Global Actions in Salesforce

Currently, a Global Action cannot be added to an object if that object is on the Detail side of the Master-Detail relationship.


So, if an object has Master Detail relationship, then that object will not be available for Global Action.

June 13, 2018

How to validate data before saving in lighting:recordForm?


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

    <div class="slds-box slds-theme_default">        
        <lightning:recordForm recordId="001f200001XrzFQAAZ" 


saveRec : function(component, event, helper) {
        var eventFields = event.getParam("fields");
        var field = 'NumberOfEmployees';
        if (eventFields.hasOwnProperty(field)) {
            if ( !eventFields.NumberOfEmployees ) {            
                var toastEvent = $A.get("e.force:showToast");
                    "title": "Error!!!",
                    "message": "Please fill Employees field",
                    "type": "error"


June 12, 2018

How to view and handle Overdue Tasks in Salesforce?

Overdue Tasks in Salesforce Classic

Overdue Tasks in Salesforce Lightning Experience

What happens if time-dependent actions sets the trigger date to past date in Salesforce?

If Salesforce recalculates the time triggers to a date in the past, Salesforce triggers the associated actions shortly after you save the record.

If a workflow rule has a time trigger set for a time in the past, Salesforce queues the associated time-dependent actions to start executing within one hour. For example, if a workflow rule on opportunities is configured to update a field 7 days before the close date, and you create an opportunity record with the close date set to today, Salesforce starts to process the field update within an hour after you create the opportunity.

Sample Scenario to set Past Time:

June 11, 2018

How to create New Sub Folder in Salesforce Reports and Dashboards?

1. Go to Reports tab.

2. Select the Folder where you wan to create the Sub Folder.

3. Click New Folder inside the Parent folder.

Sample Sub Folder view in Salesforce

Moving reports and dashboards to different folders in Salesforce

On the Reports or Dashboards page, select Move from the row level action menu. A select folder dialog box opens where you can navigate to the destination folder and save.

1. Go to Reports tab.

2. Find the report and select Move from Row level actions.

Everyone can move reports and dashboards, but you can move them only to the folders and subfolders where you have write or edit access.

Passing Parameter to batch apex in Salesforce

Sample Code:

global class SampleBatchClassWithParams implements Database.Batchable<sObject>, Database.Stateful {

    private String strParameter;

    global SampleBatchClassWithParams(String strParam, Set < Id > setIds) {
        strParameter = strParam;

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SOQL';
        return Database.getQueryLocator(query);

    global void execute(Database.BatchableContext BC, List< sObject > scope) {

    global void finish(Database.BatchableContext BC) {


Executing the Batch:

SampleBatchClassWithParams obj = new SampleBatchClassWithParams();
Database.executeBatch('test parameter', new Set < Id > {'001d000001W34vD'});

How to encode/decode URL in Salesforce Lightning component?

From Lightning component controller or helper:

var uri = "URI_Value";
var enc = encodeURI(uri);//to encode
var dec = decodeURI(enc);// to decode

From Apex:

June 8, 2018

Working with Records using REST API Salesforce

Sample Requests using Workbench:

Inserting Data Through REST API 

URL - /services/data/v20.0/sobjects/Employee__c/

Request Body:


View Data Through REST API with Specified Fields


View Data Through REST API 

URL - /services/data/v20.0/sobjects/Employee__c/a00f200000TfgpqAAB

Knowledge not available in Lightning Experience

1. Switch to Classic.

2. Enable Lightning Knowledge.

June 6, 2018

New button is not appearing in Salesforce1

Check whether the object's New button is overridden by the Visualforce page.

If yes, then make sure your Visualforce page which overrides the "New" action on the object is marked as "Available for Lightning Experience, Lightning Communities, and the mobile app". To set this, in the setup menu, go to your visualforce page (Develop > Pages), open the Visualforce page there and there you will be able to set this checkbox.

Make sure you enable this for below error also
"This page isn't available in Salesforce Lightning Experience or mobile app."

June 5, 2018

lightning:checkboxGroup to display CheckBox in horizontal direction

Sample Code:


<aura:component implements="force:appHostable" >
    <aura:attribute name="options" type="List" default="[
    {'label': 'India', 'value': 'IN'},
    {'label': 'Unites States of America', 'value': 'US'},
    {'label': 'United Kingdom', 'value': 'UK'},
    {'label': 'Australia', 'value': 'AU'}
    <aura:attribute name="selectedVal" type="List" default="IN"/>
    <div class="slds-box slds-theme_default">

     <lightning:checkboxGroup name="Checkbox Group"
                                 label="Checkbox Group"
                                 options="{! v.options }"
                                 value="{! v.selectedVal }"
                                 onchange="{! c.handleChange }"/>


Controller JS:

handleChange : function(component, event, helper) {


Style css:

.THIS .slds-form-element__control {
   display: inline-flex;



lightning:checkboxGroup Example

Sample Code:


<aura:component implements="force:appHostable" >
    <aura:attribute name="options" type="List" default="[
    {'label': 'India', 'value': 'IN'},
    {'label': 'Unites States of America', 'value': 'US'},
    {'label': 'United Kingdom', 'value': 'UK'},
    {'label': 'Australia', 'value': 'AU'}
    <aura:attribute name="selectedVal" type="List" default="IN"/>
    <div class="slds-box slds-theme_default">

    <lightning:checkboxGroup name="Checkbox Group"
                                 label="Checkbox Group"
                                 options="{! v.options }"
                                 value="{! v.selectedVal }"
                                 onchange="{! c.handleChange }"/>


Controller JS:

handleChange : function(component, event, helper) {



Error ‘!LoadWizard.errorFileWrite!extract.csv’ when using Data Loader

The folder where the extract is being stored is not accessible, is corrupt or has not been selected.

To fix this; restart the Extract process, choose the object, and select a different folder\location to store the csv file.

Make sure you have Full access to the folder where you are trying to export the records.

June 2, 2018

How to restrict users login access based on country in Salesforce?

Transaction Security feature can be used to restrict users login access based on country in Salesforce.

To know about Transaction Security and setting up use the below link


Sample Apex Code:

global class IndiaOnlySecurityPolicyCondition implements TxnSecurity.PolicyCondition {

    public boolean evaluate(TxnSecurity.Event e) {
        LoginHistory eObj = [SELECT CountryISO FROM LoginHistory WHERE Id = :e.data.get('LoginHistoryId')];
        if ( eObj.CountryISO == 'IN' ) {
            return false;
        return true; 


The above code will allow only users to log in from Country India.

Please do not do this in Production. It may not allow you to log in if set incorrectly. Try to bypass system administrator profile to avoid issues.

June 1, 2018

How to troubleshoot or check Lightning for Gmail and Sync Status?

1. Check the email id of the user in the user details.

1. Go to Lightning for Gmail and Sync Settings.

2. Click Check button in Set Sync Settings and Check Status section.

3. Check the status.

4. To find the status for any individual user, select the user in User Sync Status and click Check Status.