Developer forum

Forum » Development » Setting Primary Group

Setting Primary Group

Chris Søgaard
Chris Søgaard
Reply

Hi

Does anyone know if it's possible to set the primary group on a product from code, without having to do it directly in database with SQL scripts.

I have looked at ProductService and can see it is possible to get the ID of the primary group, but I can't seem to find anywhere to set it.

BR Chris


Replies

 
Jeppe Eriksson Agger Dynamicweb Employee
Jeppe Eriksson Agger
Reply
This post has been marked as an answer

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.

Votes for this answer: 1
 
Chris Søgaard
Chris Søgaard
Reply

Hi Jeppe

Exactly what I needed. Thank you

/Chris

 

You must be logged in to post in the forum