I’m refactoring a project from 7.1 to 7.6.2 and are currently looking on a piece of code that, to my understanding, checks if a base product has been added to a category and, if not, adds it.
I’m unsure how to add a product (either a base- or variant-product) to a category in the 7.6.2 version of Litium.
This is the ver. 7.1 version of the code I’m trying to refactor to 7.6.2:
foreach (var categoryId in item.AddToActiveCategories)
{
if (!_keyLookupService.TryGetSystemId<Category>(categoryId, out var categorySystemId))
{
continue;
}
var categoryLink = baseProduct.CategoryLinks.FirstOrDefault(x => x.CategorySystemId == categorySystemId);
if (categoryLink == null)
{
categoryLink = new BaseProductToCategoryLink(categorySystemId);
baseProduct.CategoryLinks.Add(categoryLink);
baseProductChanged = true;
}
baseProductChanged |= categoryLink.ActiveVariantSystemIds.Add(variant.SystemId);
}
My understanding is that property CategoryLinks is deprecated in Litium ver.7.6.2 and should be handled with the CategoryService. If someone has an example of how to do this or link to a example, I would be very grateful.
with some assumptions like it should be main category, and that you have a list of variants that should be active… and you should add nullchecks etc…
var category = _categoryService.Get(categoryId).MakeWritableClone();
var baseProduct = _baseProductService.Get(baseProduct);
//Try and find an existing link to the category, if it doesnt exist create
var link = category.ProductLinks.FirstOrDefault(i => i.BaseProductSystemId == baseProduct.SystemId);
if (link == null)
{
link = new CategoryToProductLink(baseProduct.SystemId) { MainCategory = true };
category.ProductLinks.Add(link);
}
//get list of variants that should be active
link.ActiveVariantSystemIds = variantIds;
_categoryService.Update(category);
You need to set which variants of your base product that should be available in this category. If you dont set the list, no variant will be active in the category.
If you open a product in backoffice, and go to the “Plan”-tab you have a list of categories there for hte base product. Then there is a “show”-button that will show you exactly which variants are active in this category. That is what the ActiveVariantSystemIds is for.