Discussions

Force 1 product per cart and quantity to one

Hello,

i'm trying to add a rule to my drupal commerce install. i need to force 1 product per cart, with max quantity = 1.

I tried:

Event: Before adding a product to the cart
Conditions : Elements: Total product quantity comparison Parameter: Order: [commerce_order] => Quantity >=1

and that's working smoothly.

But i can't find a rule to deny adding product to the cart. Already tried

Set a data value:
Selected data: commerce-order:commerce-line-items:1:quantity = 0

but it is not working. Just
Remove all products from an order
Parameter: Order to empty: [commerce_order]

works, but i'd like to remove the second product added, not the first one :)

thanks!

Posted: Jun 8, 2012

Comments

FINeX on September 17, 2012

Hi, you can create a rule to empty the cart before adding a product, moreover you can disable the qty field on cart and on the product page.

The rule I'm using is:

{ "rules_empty_cart" : {
    "LABEL" : "Empty cart",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "commerce_cart" ],
    "ON" : [ "commerce_cart_product_prepare" ],
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }
}

MD3 on September 20, 2013

For now, the best way I have found to do this is to modify the add_to_cart form and add a custom validation function that contains your business logic:

<?php
/**
  * Implementation of hook_form_FORMID_alter().
  */
function custom_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
 
$form['#validate'][] = 'custom_module_cart_add_to_cart_form_validate';
}

/**
  * Custom validation function to implement your business logic.
  */
function custom_module_cart_add_to_cart_form_validate($form, &$form_state) {
 
// Custom business logic here:
 
if (...) {
   
form_set_error('submit', t('This is the error that will be shown to the user.'));
  }
}
?>

I have suggested that we get this into rules or a new hook. You can see the status of that here: https://drupal.org/node/1658788#comment-7879639