How to get the Salesforce Instance Server URL from APEX Trigger?

Using trigger we can get the Salesforce Server URL, below is the example:

for example, used below codes in before insert or before update triggers from account object,


trigger accountBeforeInsert on Account (before insert, before update) {
if(trigger.isBefore == true && (trigger.isInsert == true || trigger.isUpdate == true)) {
URL currentURL = URL.getCurrentRequestUrl();
URL comparisonURL = new URL(URL.getSalesforceBaseUrl().toExternalForm() + Page.YOUR_VF_PAGE_URL.getUrl());
system.debug('currentURL:::'+ currentURL);
system.debug('comparisonURL:::'+ comparisonURL);
boolean knownPath = currentURL.getPath() == comparisonURL.getPath();

if(knownPath == true) {
// Currently You comming from Custom VF Page ("YOUR_VF_PAGE_URL")
} else {
// Currently You Comming from Standard Account Page Creation.
}
}
}

Note: if you view and submitting the page from “YOUR_VF_PAGE_URL” then you can get the values true in the “knownPath” variables.
Ex:
https://c.cs8.visual.force.com/apex/YOUR_VF_PAGE_URL?Id=00UL0000001Yyvh
knownPath = TRUE;

if you trying to create a new account from standard page
https://cs8.salesforce.com/001/e?retURL=%2F001%2Fo&nooverride=1
knownPath = FALSE;

Written by 

3x Salesforce MVP | Platform Champion | 18x Salesforce Certified | MuleSoft Certified | 8x Trailhead Ranger | TechForce Services | Sydney | Australia

Leave a Reply

Your email address will not be published.

*