How Do I Programmatically Display Base Products That Have Variant Products in Hybris Commerce?

This tutorial provides step by step instructions how to display base products that have variant products using Groovy.

Step by Step Instructions

1. Goto to HAC in your Web browser. (If Hybris is running on your local machine, type https://localhost:9002/ in your Web browser URL)

2. Type your user name and password once HAC is displayed. (The following screenshot displays the HAC login page with username and password provided)

3. Once you've logged in successfully, click on Console -> Scripting Languages

4.  Copy and paste the following code into the Console window:

import de.hybris.platform.servicelayer.search.FlexibleSearchService
import de.hybris.platform.servicelayer.search.SearchResult;
import de.hybris.platform.core.model.product.ProductModel
import de.hybris.platform.variants.model.VariantProductModel;

Map<String, Object> params = new HashMap<String, Object>();
String query = "SELECT {p:pk} FROM {Product AS p}"
params = null;

FlexibleSearchService fss = spring.getBean("flexibleSearchService")

final SearchResult<ProductModel> searchResult = fss.search(query, params);

for (final ProductModel product : searchResult.getResult()) {
   if (product.getVariants().size() > 0) {
      println("Product Code: " + product.getCode() + " Product Name: " + product.getName() + " --- Number of Variants: " + product.getVariants().size());
      for (final VariantProductModel variant : product.getVariants()) {
        println "----> Variant Product Code: "+variant.getCode() + ", Variant Product Name: " + variant.getName();
      }
   }
}
Your Console should resemble the following:

5. Click on Execute

6. Next, Click on the Output tab, you should see the base products have that have variant products in your Hybris Commerce implementation.

(My list of variant products will be quite different than yours, but your results will appear in this format)

7. Tutorial is complete, now you know how to programmatically display base products that have variant products in Hybris Commerce.

Marc Raygoza

Marc is the Founder of HybrisArchitect.com.
He enjoys helping others learn more about SAP Commerce Cloud (Hybris). Marc is a SAP Commerce Certified Professional and has held the role of SAP Commerce Cloud Architect at Deloitte, PwC, Brillio (a Bain Company), and Nasty Gal. Marc holds an M.S. Software Engineering from Carnegie Mellon University and a B.S. in Accountancy from California State University, Fresno. He can be reached at: mraygoza@hybrisarchitect.com

You may also like...

Popular Posts