I want to disable the ability of adding a product twice to the shopping cart.
Is there a way to prevent or prompt a message when a user tries to add the same product twice?
I want to disable the ability of adding a product twice to the shopping cart.
Is there a way to prevent or prompt a message when a user tries to add the same product twice?
<?php
/**
* Implements hook_form_FORMID_alter().
*/
function mymodule_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
$product_ids = mymodule_get_products_in_cart();
$line_item = $form_state['line_item'];
$product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
if ($product->type == 'program') {
if (in_array($product->product_id, $product_ids)) {
// Product is already in cart! We only want to allow a quantity of 1,
// so disable the submit button and change its text accordingly
$form['submit']['#disabled'] = TRUE;
$form['submit']['#value'] = t('Already in cart');
}
}
}
/**
* Return the product_id values for all products in the cart
*
* @return
* An array of product ids
*/
function mymodule_get_products_in_cart() {
$product_ids = &drupal_static(__FUNCTION__);
if (!isset($product_ids)) {
global $user;
$product_ids = array();
$order = commerce_cart_order_load($user->uid);
if ($order) {
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
$product_wrapper = $line_item_wrapper->commerce_product;
$product_ids[] = $product_wrapper->product_id->value();
}
}
}
return array_unique($product_ids);
}
?>
Checkout #5 of the following link - it shows how to do it if you have the stock module activated and disables the add to cart button.
https://www.drupal.org/node/1658788
Quote:
The commerce-stock add the event : "Check if a product add to cart form should be enabled" which is exactly what we want to do.
I added 2 conditions inside an "AND" condition set:
Data comparison (to check if the product page is of a product type B) : Parameter: Data to compare: [commerce-product:type], Data value: Product B
"Order contains products of particular product types" and select your other product type.
And then the magic comes from the action : "Advanced configuration of the add to cart form", also added by the commerce-stock module. With the following parameters : Parameter: Hide the Quantity field if it is visible: true, The text to set the action to: not compatible with..., Add a class to the add to cart form: no-eshop, Disable the add to cart?: true, Clear the submit array first: false, Clear the validation array first: false
I'm not sure if this is a bug. if you tried to add the same item to the cart more than once it will increment the item count instead of adding a duplicate item.