Developer forum

Forum » Ecommerce - Standard features » Check if a product is in cart

Check if a product is in cart

Adrian Ursu Dynamicweb Employee
Adrian Ursu
Reply

Hi guys,

I have a DW9 project where I need to limit the add to cart functionality and only add products which are not already in cart.
I am using ProductViewModel in the add to cart logic, and I was wondering if there is any way to simply check if a Product is already in cart.
I remember that the template version had a tag "ProductIsInCart" or something similar.

Thank you,
Adrian
 


Replies

 
Imar Spaanjaars Dynamicweb Employee
Imar Spaanjaars
Reply

Not that I am aware of. But I guess you can do something like:

bool isInCart = cart.Products.Any(x => x.Number = Model.Number);

You may need more restrictions than number if you haver things like Units to consider.

Imar

 
Nicolai Pedersen Dynamicweb Employee
Nicolai Pedersen
Reply

This extension is from Dynamiccweb 10:

/// <summary>
    /// Checks if the product is in the cart
    /// </summary>
    /// <param name="product">The product view model</param>
    /// <param name="orderContextId">The order context ID</param>
    /// <returns>True if the product is in the cart, false otherwise</returns>
    public static bool IsProductInCart(this ProductViewModel product, string orderContextId = null)
    {
        Orders.Order cart;
        if (!string.IsNullOrEmpty(orderContextId))
        {
            Orders.OrderContext orderContext = Services.OrderContexts.GetOrderContextById(orderContextId);
            if (orderContext == null)
            {
                return false;
            }
            cart = Common.Context.GetCart(orderContext);
        }
        else
        {
            cart = Common.Context.Cart;
        }
 
        if (cart != null)
        {
            return cart.IsProductInOrder(product.Id, product.VariantId);
        }
 
        return false;
    }
 
Adrian Ursu Dynamicweb Employee
Adrian Ursu
Reply

Hi guys,

Thank you both for the suggestions.
I will see which one works for my case.

Thank you,
Adrian

 

You must be logged in to post in the forum