Posted on 22/07/2021 13:09:52
Hi Chris,
It can be done. Take a look at the GroupService (Dynamicweb.Ecommerce.Services.ProductGroups).
The procedure is a little different depending on whether you can to create a new group relation and set that as the primary, or whether you want to set one of the current relations as primary. Code examples below.
public static void SetExistingRelationPrimary(string productId, string groupIdToSetPrimary)
{
// Get all group relations for the given product
var relations = Dynamicweb.Ecommerce.Services.ProductGroups.GetProductGroupRelations(productId);
// Flip the IsPrimary value for the relevant relations
foreach (var relation in relations)
{
// Get whether the relation is currently primary
var wasPrimaryBefore = relation.IsPrimary;
// Set whether the relation should be primary
relation.IsPrimary = relation.GroupId == groupIdToSetPrimary;
// Determine whether Primary state has changed
var wasPrimaryButIsNoLonger = wasPrimaryBefore && !relation.IsPrimary;
var isPrimaryButWasntBefore = !wasPrimaryBefore && relation.IsPrimary;
if (wasPrimaryButIsNoLonger || isPrimaryButWasntBefore)
{
// Save relation if the IsPrimary value was changed
Dynamicweb.Ecommerce.Services.ProductGroups.Save(relation);
}
}
}
public static void SetNewRelationPrimary(string productId, string groupIdToRelateToProduct)
{
// Get all group relations for the given product BEFORE we create the new one -- makes it easier for us
var relations = Dynamicweb.Ecommerce.Services.ProductGroups.GetProductGroupRelations(productId);
// Create the new relation
var newRelation = Dynamicweb.Ecommerce.Services.ProductGroups.CreateProductGroupRelation(productId, groupIdToRelateToProduct, isPrimary: true);
// Flip the IsPrimary value for the relevant relations
foreach (var relation in relations)
{
if (relation.IsPrimary)
{
relation.IsPrimary = false;
Dynamicweb.Ecommerce.Services.ProductGroups.Save(relation);
}
}
}
I hope that helps you proceed.
- Jeppe
EDIT: Changed formatting to improve readability.