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 

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

Your email address will not be published. Required fields are marked *