1

Is there a way to programmatically build or retrieve a Product's url on a storefront using its ID?

I do see that the ID is included in the final URL:

https://(domain).force.com/(community)/s/product/hamilton-beach-coffee-maker/01t4W00000B6tnjQAB

But I wonder if there is a safe / robust way to get this URL either in a Lightning component or Apex ?

1 Answer 1

2

Hey @slaughterize good day.

we had this instance on our project and would like to share how we constructed the URLs programmatically for consumption.

Think of it as 2 parts:

BaseURL: https://(domain).force.com/(community)/s

Product detail page URL in your community: /product/hamilton-beach-coffee-maker/01t4W00000B6tnjQAB

Now to get the BaseURL, luckily we can leverage SiteDetail object and get the secureURL which is explained by benahm in this StackExchange link: Get Site URL from apex and just append that secureUrl with /s string

All that is left is to construct the product detail page URL:

Builder

In my case the product detail page url is: /product/:recordName/:recordId

  1. product is the base url for the product detail page. if you want other base url name for this page you can customize this in the community builder
  2. recordName becomes like a slug ([Some] Product) -> some-product
  3. recordId of the entitled product
    // Assuming you have a method which returns the base url
    public static void retrieveStoreUrl() {
        Site mySite = [select Id from Site where Name = 'MySite'];
        SiteDetail mySiteDetail = [select SecureURL from SiteDetail where DurableId = :mySite.Id];
        return mySiteDetail.SecureUrl + '/s';
    }


    // We have a method which basically converts the string you passed to lowercase, removes any special character and replaces whitespaces with dash character
    // Example the product name is: [Some] Product Name
    // It will just convert the string to this value:  some-product-name
    public static void stringToSlug(String stringToConvert) {
        return stringToConvert.toLowerCase().trim().replaceAll('[^a-z0-9\\s]+', '').replaceAll('[\\s]+', '-');
    }

    // Now we begin constructing the url
    public static void returnProductUrl(Product2 entitledProduct) {
        String baseUrl = SomeClass.retrieveStoreUrl();

        // Convert the string to slug
        String productSlug = SomeUtilityClass.stringToSlug(entitledProduct.Name);

        // All thats left is to concatenate all the required values
        return baseUrl + '/product/' + productSlug + '/' + entitledProduct.Id; // Returns (https://(domain).force.com/buy/s/product/some-product-name/01t6F000005DgTpQAK)
    }
1
  • Thank you very much for posting this answer. Very useful Commented Oct 27, 2022 at 23:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .