Share Your Experience With Others

Getting Community Url in Apex

Hi Guys, Sometimes we need community url in our controller to redirect our user to the portal with a particular id.
I search a lot about it that how we can get the community url directly by some apex predefined method but this one solution i have found. For example you have this:

Community Url: https://communityurl.cs92.force.com/customers
and Community Name is Testing Community
  • Get url from Domain object:
  • Domain d=[SELECT Domain FROM Domain where domain like 'community%' limit 1];
    Result : communityurl.cs92.force.com
  • This /customers is the Community UrlPathPrefix which you can fetch from Network object like this:
  • Network n=[select name, UrlPathPrefix FROM Network where name like '%Community' limit 1];
    Result: Name : Testing Community and UrlPathPrefix : customers
  • You can use custom labels for ‘community%’ and for ‘%community’.
  • If you are only using the community url then you have no need of network object query.
  • Now you can make your community url like this in apex :
  • String communityUrl='https://'+d.Domain+'/'+n.UrlPathPrefix+'/CommunitiesPage?Id='+opplist[0].id;
  • where CommunitiesPage is the visualforce page name and opplist[0].id is the opportunity id.
  • My personal suggestion is if you want to avoid these soql queries use custom label to store the community url in each org.
  • Because in every salesforce org the instance will be change so may be the ‘community%’ and for ‘%community’ will not work there.

    Your suggestions are always welcome.

Leave a comment