Monday, September 24, 2018

How to Redirect to URL Based on Theme and Site Name in Salesforce

If you are Redirecting URL From Button and That Button Used In Different Places Like Community, Partner Portal, Lightning Experience.
In Lightning Experience, URL is Different Compare to the Classic Theme URL.
So First You Need to check the Current User Theme Based On Theme You Need to Redirect to The URL.
Check Bellow themes are available in Salesforce.

Theme1 —> Obsolete Salesforce theme
Theme2 —> Salesforce Classic 2005 user interface theme
Theme3 —> Salesforce Classic 2010 user interface theme
Theme4d —> Modern “Lightning Experience” Salesforce theme
Theme4t —> Salesforce1 mobile Salesforce theme
PortalDefault —> Salesforce Customer Portal theme
Webstore —> Salesforce AppExchange theme

To Check the Current theme in Visualforce page use below Global Variables

{!$User.UIThemeDisplayed}
OR
In Apex UserInfo.getUiThemeDisplayed().
To Check Site Name in Visualforce Page Use Global Variable
{!Site.Name}
In Portal or Communities URL is Different like
https://Baseurl/<portalName>/apex/apexpage/
Demo:
Check Below VisualForce Page to understand easily
<apex:page standardController="Account" showHeader="false" sidebar="false">
    <script>   
     if(typeof sforce !== 'undefined' && sforce !== null && '{!$User.UIThemeDisplayed}' === 'Theme4d') {
         window.open('/apex/ApexTestPage?id={!Account.Id}');
         sforce.one.back(true);
     }
     else if('{!$User.UIThemeDisplayed}' !== 'Theme4d' && ('{!$Site.Name}' == undefined || '{!$Site.Name}'  == '' || '{!$Site.Name}'  == null)) {
        window.open('/apex/ApexTestPage?id={!Account.Id}','_blank');
        window.top.location = '/{!Account.Id}';
     }
     else if('{!$Site.Name}' != null || ('{!$User.UIThemeDisplayed}' === 'Theme4d' && '{!$Site.Name}' != null)) {
         var siteName = '{!$Site.Name}';
         siteName = siteName.toLowerCase(); 
         window.open('/'+siteName+'/apex/ApexTestPage?id={!Account.Id}','_blank');
         window.top.location = '/'+siteName+'/{!Account.Id}';
     }
    </script>
</apex:page>

for Testing, Create Detail Page Button on Account(I Used Standard Controller as Account), Based on Your Preference create button and add the Page.
After that Add Button in Layouts based on your Preferences Like(Community, Portal, Lightning Experience).

Note: You can change the Script in Visualforce Page based on Your Requirement and you Can Extend the Functionality Further.

References:
Site Reference In Visualforce Page
sforce Methods
Let us know if you have any queries.

Happy Learning!!!

No comments:

Post a Comment