allBlogsList

Extending the Sitecore Commerce Connect product base class for custom product attributes

Sitecore Commerce Connect default product repository is Sitecore.Commerce.Data.Products.ProductRepository

If we want to extend the sitecore commerce connect product template to include custom product properties, we need to create our own repository and an extended product class

Here are the steps involved in extending product base class:

1. Template changes: Create a template in Sitecore with all the custom fields. Add it to the base product class inheritance. I am not going to cover this as this is simple sitecore stuff.

2. Define a custom product class that includes the fields defined in the new sitecore template you just created in step 1.

public class Product : Sitecore.Commerce.Entities.Products.Product

3. Create a custom repository inheriting from default commerce connect product repository. Add default updateentity method. Step 4 has the class details.

4. Add logic to populate the new custom fields in the custom product class created in Step 2.

internal class ProductRepository : Sitecore.Commerce.Data.Products.ProductRepository
    {
        protected override void UpdateEntityItem(Item entityItem, Product entity)
        {
            base.UpdateEntityItem(entityItem, entity);
            var customProduct = entity as CustomEntities.Product;

            if (customProduct == null)
            {
                return;
            }
            using (new EditContext(entityItem))
            {
                entityItem["Unit of Measure"] = customProduct.UnitOfMeasure;
                CheckboxField isVariant = new CheckboxField(entityItem.Fields["Is Variant"]);
                isVariant.Checked = customProduct.IsVariant;                

                if (!string.IsNullOrEmpty(AvailableUnitOfMeasureDefaultID))
                {                  
                    entityItem["Available Unit of Measures"] = AvailableUnitOfMeasureDefaultID;
                }
            }
        }


       protected override void PopulateEntity(Item entityItem, Product entity)
        {
            base.PopulateEntity(entityItem, entity);
            var customProduct = entity as CustomEntities.Product;
            if (customProduct == null)
            {
                return;
            }
            customProduct.UnitOfMeasure = entityItem["Unit of Measure"];
            customProduct.IsVariant = new CheckboxField(entityItem.Fields["Is Variant"]).Checked;        
        }

5. Add a new config file, Replace the base commerce product class with the new custom class and Change the product repository type to new type you just created.

<commerce.entities>