Posts Tagged ‘RecursiveChildProducts’

CategoryConfiguration class is used to configure the pre-loaded properties of a category object which includes child category and products.  Through this object, we can tell commerce server whether to fetch all products under a category (including sub categories) or products under that category only. In this article I am explaining how to fetch category products with the help of CategoryConfiguration class.

Requirement:

1.       If the category is root or parent then show all the products under that category (including products in sub categories).

2.       If the category is sub-category and doesn’t have any categories under it then show only those products.

Pre-requisites:

I created a catalogName “MySite” and top category named “Dance”. Under “Dance”, I have created two categories named “classic dance” and “break dance”. “Dance” category is having two products and sub-categories having one product each.

            string catalogName = “Mysite”;

            string categoryName = “Break Dance”;

            CatalogContext catalogContext = CommerceContext.Current.CatalogSystem;

            ProductCatalog catalog = catalogContext.GetCatalog(catalogName);

            CategoryConfiguration categoryConfig = new CategoryConfiguration();

            categoryConfig.RecursiveChildProducts = false;

           

            ProductCollection productCollection;

            CategoryCollection categoryCollection = null;

 

            if (categoryName == string.Empty)

            {

                productCollection = catalog.GetRootCategory(categoryConfig).ChildProducts;

            }

            else

            {

                Category category = null;

                category = catalog.GetCategory(categoryName, categoryConfig);

                categoryCollection = category.ChildCategories;

                if (categoryCollection.Count > 0)

                {

                    categoryConfig.RecursiveChildProducts = true;

                    category = catalog.GetCategory(categoryName, categoryConfig);

                }

                productCollection = category.ChildProducts

            }

            Response.Write(productCollection.Count.ToString());

 

In the above code, we are checking whether the category is having any child categories, if yes then we are getting all products under that category by setting the catalogConfiguration class property – RecursiveChildProducts to true. If the category doesn’t have any sub-categories then the products at the root are returned.

If I pass “Dance” value to category variable then I will get four products and If I pass “Break Dance” value to category variable then I will get one product.

Related Articles


If you like this post, please click on our sponsor advertisement.


Follow me on Google+
Add to circles

In 0 people's circles

Sign up for Newsletter