Discussions

Rule for checking shopping cart (order) for duplicated items

I am trying to create a rule to check order for duplicated products. I am selling digital goods and it does not make sense for customer to buy two same digital products.

So I created a rule that loops through commerce order line items to find duplicates. When finds duplicates, it should remove the newly added product from order. However I am not able to distingiush between products that are in shopping cart already and newly added product.
My rule is reacting on event „After adding a product to the cart“ and is looping through „cart-order:commerce-line-items“.

The component that is looping through order line items has condition: „List contains item“ , where List is „cart-order:commerce-line-items“, and the item to check for is a variable passed to component „lineitem-added-to-cart“.

Currently when I add product to the cart, the condition is always evaluated as True and product is removed from the cart.

Screencast in this thread gave me the basic clue how to loop through line items in order, thank you Randy very much! http://www.drupalcommerce.org/discussions/2491/solved-removing-line-item....
However I still could not figure out solution for my specific purpose. Any help will be much appreciated!

Posted: Jun 6, 2012

Comments

sketman on June 15, 2012

1. Create rule, name it; Event: before adding a product to the cart
2. You can add there conditions if you wish. I am chcecking here is product is digital or not.
3. In Actions add Loop through commerce-order:commerce-line-items
4. Create component, single rule, name it
5. Create following variables of the component and name them as you wish:
- Commerce line item (line item of the order from the loop of the main rule)
- Commerce product (product added to the cart)
6. Add condition to the component: Entity has field, Entity: [line-item-in-order], Field: commerce_product. this will bring us the product from actual line item in current order (shopping cart).
7. Add condition to the component: Data comparison. Data to compare: line-item-in-order:commerce-product with product-added-to-cart (variable brought from the main rule)
8. Add action to the component: Remove an item from a list. List: [order:commerce-line-items], Item to remove: [line-item-in-order]. This will completely remove duplicated product from the shopping cart and from the order as well.
9. Eventually add another actions. At least Display some message to the user to inform him/her that the item has been removed sounds sensible.
10. Come back to your main rule created in step 1. Add action to the loop and select the component you have just created in steps 4. - 9. and set the variables.
11. You are done. Chcek it, it should work