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 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply