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.
knownPath = TRUE;

if you trying to create a new account from standard page
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.