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

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

now().format()
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());

Output:


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

http://www.infallibletechie.com/2014/06/similar-opportunities-in-salesforce.html

Sample Action in Einstein Bot

Sample code:

Apex Class:

public with sharing class ChatBotUtil {

    public class ChatBotCertInput {
        @InvocableVariable(required=true)
        public String cert;
    }

    public class ChatBotCertOutput {
        @InvocableVariable
        public String certName;
        @InvocableVariable
        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';
            }
            results.add(item);
        }
        return results;
    }
    
}

Einstein Builder:



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.

For other limitations in Platform Event - https://developer.salesforce.com/docs/atlas.en-us.212.0.platform_events.meta/platform_events/platform_event_limits.htm

Sample Platform Event Example - http://www.infallibletechie.com/2017/06/platform-events-in-salesforce.html

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


Einstein Bot

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.


Check the below 2 mins video

https://youtube.com/watch?feature=youtu.be&v=14l6Blr0jM0

To setup, follow the steps in below link

http://www.infallibletechie.com/2018/06/how-to-setup-einstein-bot-in-salesforce.html

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.

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.

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.

https://success.salesforce.com/ideaView?id=0873A000000CMPMQA4


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

How to validate data before saving in lighting:recordForm?

Component:

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

    <div class="slds-box slds-theme_default">        
        <lightning:recordForm recordId="001f200001XrzFQAAZ" 
                              objectApiName="Account"
                              layoutType="Full" 
                              mode="Edit" 
                              onsubmit="{!c.saveRec}"/>        
    </div>
    
</aura:component>

Controller:

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

Output:


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:


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.


Note:
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:


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:

{
"Employee__c":"Test",
"Age__c":19
}


View Data Through REST API with Specified Fields


/services/data/v20.0/sobjects/Employee__c/a00f200000Tfgpq?fields=Name,Employee_Name__c,Age__c

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.


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.




lightning:checkboxGroup to display CheckBox in horizontal direction

Sample Code:

Component:

<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 }"/>
    </div>
    

</aura:component>

Controller JS:

({
handleChange : function(component, event, helper) {
alert(component.get("v.selectedVal"));
}

})

Style css:

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

}

Output:


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.

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

http://www.infallibletechie.com/2016/11/transaction-security-in-salesforce.html

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.

Note:
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.

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

Note:
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.