Category Archives: Salesforce

Webservice Callout From Apex Trigger

In certain scenarios, we need to make the webservice callout from the apex trigger to call an external webservice. We cannot call external web services synchronously from triggers, because calling a web service synchronously from triggers will hold up the database transaction until the callout completed. This will impact performance for other transactions. In this scenario we can invoke callouts from triggers by encapsulating the callouts in @future methods. Here is an example, how to invoke webservice callouts from trigger.

Apex Class:

public class LeadTriggerHandler {
    
    @future (callout=true)
    public static void sendLeadInfo(string firstName, string lastName, string email) {
        try{
            HttpRequest request = new HttpRequest();
            HttpResponse response = new HttpResponse();
            Http http = new Http();
            
            request.setEndpoint('Your Endpoint URL');
            request.setHeader('Content-Type','application/json'); 
            request.setMethod('POST');
            request.setBody('fname='+EncodingUtil.urlEncode(firstName, 'UTF-8')+'&lname='+EncodingUtil.urlEncode(lastName, 'UTF-8')
                            '&email='+EncodingUtil.urlEncode(email, 'UTF-8'));
            request.setCompressed(true);
            
            response = http.send(request);
            if (response.getStatusCode() == 200) {
                System.debug('Response-' + response);
            }
        }
        catch(System.CalloutException e){
            System.debug('Error-' + e.getMessage());   
        }
    }
}

Apex Trigger:

trigger LeadTrigger on Lead (after insert) {
    
    for (Lead objLead : Trigger.new) {
        //make webservice callout 
        LeadTriggerHandler.sendLeadInfo(objLead.FirstName, objLead.LastName, objLead.Email);
    }
}

$Action Global Variable in Salesforce

$Action is a global variable. All objects support basic actions, such as new, clone, view, edit, list, and delete. The $Action global also references actions available on many standard objects.

Example:

<apex:page standardController="Account">
    
    <!--Create Account New Record-->
    <apex:outputLink value="{!URLFOR($Action.Account.New)}">
        Creating New Account
    </apex:outputLink>
    
    <!--Edit Account Record -->
    <apex:outputLink value="{!URLFOR($Action.Account.Edit, Account.Id)}">
        Editing record
    </apex:outputLink>
    
    <!--Delete Account Record-->
    <apex:outputLink value="{!URLFOR($Action.Account.Delete, Account.Id)}">
        Deleting Account Record
    </apex:outputLink>
    
    <!--Navigate to Account List view-->
    <apex:outputLink value="{!URLFOR($Action.Account.List, $ObjectType.Account)}">
        Go to the Account List View
    </apex:outputLink>
    
    <!--Navigate to Account Tab-->
    <apex:outputLink value="{!URLFOR($Action.Account.Tab, $ObjectType.Account)}">
        Go to the Account tab
    </apex:outputLink>
</apex:page>

You can reference following actions with the $Action global variable and the objects on which you can perform those actions.

Value Description Objects
Accept Accept a record.
  • Ad group
  • Case
  • Event
  • Google campaign
  • Keyword
  • Lead
  • Search phrase
  • SFGA version
  • Text ad
Activate Activate a contract. Contract
Add Add a product to a price book. Product2
AddCampaign Add a member to a campaign. Campaign
AddInfluence Add a campaign to an opportunity’s list of influential campaigns. Opportunity
AddProduct Add a product to price book. OpportunityLineItem
AddToCampaign Add a contact or lead to a campaign.
  • Contact
  • Lead
AddToOutlook Add an event to Microsoft Outlook. Event
AdvancedSetup Launch campaign advanced setup. Campaign
AltavistaNews Launch www.altavista.com/news/.
  • Account
  • Lead
Cancel Cancel an event. Event
CaseSelect Specify a case for a solution. Solution
ChangeOwner Change the owner of a record.
  • Account
  • Ad group
  • Campaign
  • Contact
  • Contract
  • Google campaign
  • Keyword
  • Opportunities
  • Search phrase
  • SFGA version
  • Text ad
ChangeStatus Change the status of a case.
  • Case
  • Lead
ChoosePricebook Choose the price book to use. OpportunityLineItem
Clone Clone a record.
  • Ad group
  • Asset
  • Campaign
  • Campaign member
  • Case
  • Contact
  • Contract
  • Event
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Product
  • Search phrase
  • SFGA version
  • Text ad
  • Custom objects
CloneAsChild Create a related case with the details of a parent case. Case
CloseCase Close a case. Case
Convert Create a new account, contact, and opportunity using the information from a
lead.
Lead
ConvertLead Convert a lead to a campaign member. Campaign Member
Create_Opportunity Create an opportunity based on a campaign member. Campaign Member
Decline Decline an event. Event
Delete Delete a record.
  • Ad group
  • Asset
  • Campaign
  • Campaign member
  • Case
  • Contact
  • Contract
  • Event
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Opportunity product
  • Product
  • Search phrase
  • SFGA version
  • Solution
  • Task
  • Text ad
  • Custom objects
DeleteSeries Delete a series of events or tasks.
  • Event
  • Task
DisableCustomerPortal Disable a Customer Portal user. Contact
DisableCustomerPortalAccount Disable a Customer Portal account. Account
DisablePartnerPortal Disable a Partner Portal user. Contact
DisablePartnerPortalAccount Disable a Partner Portal account. Account
Download Download an attachment.
  • Attachment
  • Document
Edit Edit a record.
  • Ad group
  • Asset
  • Campaign
  • Campaign member
  • Case
  • Contact
  • Contract
  • Event
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Opportunity product
  • Product
  • Search phrase
  • SFGA version
  • Solution
  • Task
  • Text ad
  • Custom objects
EditAllProduct Edit all products in a price book. OpportunityLineItem
EnableAsPartner Designate an account as a partner account. Account
EnablePartnerPortalUser Enable a contact as a Partner Portal user. Contact
EnableSelfService Enable a contact as a Self-Service user. Contact
FindDup Display duplicate leads. Lead
FollowupEvent Create a follow-up event. Event
FollowupTask Create a follow-up task. Event
HooversProfile Display a Hoovers profile.
  • Account
  • Lead
IncludeOffline Include an account record in Connect Offline. Account
GoogleMaps Plot an address on Google Maps.
  • Account
  • Contact
  • Lead
GoogleNews Display www.google.com/news.
  • Account
  • Contact
  • Lead
GoogleSearch Display www.google.com.
  • Account
  • Contact
  • Lead
List List records of an object.
  • Ad group
  • Campaign
  • Case
  • Contact
  • Contract
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Product
  • Search phrase
  • SFGA version
  • Solution
  • Text ad
  • Custom objects
LogCall Log a call. Activity
MailMerge Generate a mail merge. Activity
ManageMembers Launch the Manage Members page. Campaign
MassClose Close multiple cases. Case
Merge Merge contacts. Contact
New Create a new record.
  • Activity
  • Ad group
  • Asset
  • Campaign
  • Case
  • Contact
  • Contract
  • Event
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Search phrase
  • SFGA version
  • Solution
  • Task
  • Text ad
  • Custom objects
NewTask Create a task. Task
RequestUpdate Request an update.
  • Contact
  • Activity
SelfServSelect Register a user as a Self Service user. Solution
SendEmail Send an email. Activity
SendGmail Open a blank email in Gmail.
  • Contact
  • Lead
Sort Sort products in a price book. OpportunityLineItem
Share Share a record.
  • Account
  • Ad group
  • Campaign
  • Case
  • Contact
  • Contract
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Search phrase
  • SFGA version
  • Text ad
Submit for Approval Submit a record for approval.
  • Account
  • Activity
  • Ad group
  • Asset
  • Campaign
  • Campaign member
  • Case
  • Contact
  • Contract
  • Event
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Opportunity product
  • Product
  • Search phrase
  • SFGA version
  • Solution
  • Task
  • Text ad
Tab Access the tab for an object.
  • Ad group
  • Campaign
  • Case
  • Contact
  • Contract
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Product
  • Search phrase
  • SFGA version
  • Solution
  • Text ad
View View a record.
  • Activity
  • Ad group
  • Asset
  • Campaign
  • Campaign member
  • Case
  • Contact
  • Contract
  • Event
  • Google campaign
  • Keyword
  • Lead
  • Opportunity
  • Opportunity product
  • Product
  • Search phrase
  • SFGA version
  • Solution
  • Text ad
  • Custom objects
ViewAllCampaignMembers List all campaign members. Campaign
ViewCampaignInfluenceReport Display the Campaigns with Influenced Opportunities report. Campaign
ViewPartnerPortalUser List all Partner Portal users. Contact
ViewSelfService List all Self-Service users. Contact
YahooMaps Plot an address on Yahoo! Maps.
  • Account
  • Contact
  • Lead
YahooWeather Display http://weather.yahoo.com/. Contact

Salesforce BusinessHours Calculation

//Get the default business hours
Id businessHourId = [SELECT Id FROM BusinessHours WHERE IsDefault = true].Id;

//Get the next date when business hours are open. If the specified target date falls within business hours, this target date is returned.
Datetime targetDate = system.today();
Datetime nextDate = BusinessHours.nextStartDate(businessHourId, targetDate);

//Check target date occurs within business hours. Holidays are included in the calculation.
Datetime targetDate = system.today();
Boolean isWithinBusinessHour = BusinessHours.isWithin(businessHourId, targetDate);

//Get the difference between a start and end Datetime based on a specific set of business hours in milliseconds.
Datetime startDT = system.today();
Datetime endDT = DateTime.Now().AddDays(2);
Long difference = BusinessHours.diff(businessHourId, startDT, endDT);
Double hours = difference/3600000;

//Adds an interval of time from a start Datetime traversing business hours only. Returns the result Datetime in the local time zone.
Datetime startDT = system.today();
Long intervalMilliseconds = 50000;
Datetime targetDT = BusinessHours.add(businessHourId, startDT, intervalMilliseconds);

Batch Apex With Webservice Callout

To make a Webservice callout in batch Apex, we have to implement Database.AllowsCallouts interface in the class definition. Here is an example to make webservice callout in batch apex.

Batch Apex:

global class AccountBatchApex implements Database.Batchable<sObject>, Database.AllowsCallouts{
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
        return Database.getQueryLocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        
        for (Account acc : scope){
            if(acc.Type.equals('Customer - Direct')){
                try{
                    HttpRequest request = new HttpRequest();
                    HttpResponse response = new HttpResponse();
                    Http http = new Http();
                    
                    String username = 'YourUsername';
                    String password = 'YourPassword';
                    Blob headerValue = Blob.valueOf(username + ':' + password);
                    String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
                    
                    request.setHeader('Authorization', authorizationHeader);
                    request.setHeader('Content-Type', 'application/json');
                    request.setEndpoint('Your Endpoint URL');
                    request.setMethod('POST');
                    request.setBody('Information to Send');
                    response = http.send(request);
                    if (response.getStatusCode() == 200) {
                        String jsonResponse = response.getBody();
                        System.debug('Response-' + jsonResponse);
                    }
                }
                catch(Exception){
                    System.debug('Error-' + e.getMessage());   
                }
            }
        }
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
}

Note: Total number of callouts (HTTP requests or Web services calls) is 100, that means if you have one callout in your execute method you can keep batch size as 100.

URL Class in Salesforce

//Create a new account called "Test Account" that we will create a link for later.
Account acc = new Account(Name = 'Test Account');
Insert acc;

//Get the base URL.
String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
System.debug('Base URL: ' + baseURL);       

//Get the URL for the current request.
String currentReqURL = URL.getCurrentRequestUrl().toExternalForm();
System.debug('Current request URL: ' + currentReqURL);        

//Create the account URL from the base URL.
String accURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + acc.Id;
System.debug('URL of a particular account: ' + accURL); 

//Get some parts of the base URL.
System.debug('Host: ' + URL.getSalesforceBaseUrl().getHost());   
System.debug('Protocol: ' + URL.getSalesforceBaseUrl().getProtocol());

//Get the query string of the current request.
System.debug('Query: ' + URL.getCurrentRequestUrl().getQuery());