Drupal Commerce | Restrict Qty

There might be some cases where we want to to sell only one Qty of each product per order. So it will need restriction where user can add only 1 item of each type. Luckily, Drupal commerce rules are there . you just need to set a rule with event “After adding item to cart” and action “Set a data value” to set “commerce-line-item:quantity” to 1, that’s it, you are done.

Now what about hiding “add to cart” button if Item is already sold to some user. see below two functions, where one function check if user ever ordered particular product or not, and in second, we alter add to cart form to hide “add to cart” button if user purchased it previously.

* Implements hook_form_FORM_ID_alter().
function example_form_alter(&$form, &$form_state, $form_id) {

// Loop over the quantity textfields on the form.
if($form_id == "views_form_commerce_cart_form_default") {
foreach (element_children($form['edit_quantity']) as $key) {
$line_item_id = $form['edit_quantity'][$key]['#line_item_id'];
$line_item = commerce_line_item_load($line_item_id);

// If it's for a donation line item...
if ($line_item->type == 'product_display' ) {
// Turn it into a simple text representation of the quantity.
$form['edit_quantity'][$key]['#type'] = 'value';
$form['edit_quantity'][$key]['#suffix'] = check_plain($form['edit_quantity'][$key]['#default_value']);

if ((strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0)) {
$nod = menu_get_object();
if(product_purchased($nod->nid)) {
$form['#prefix'] = '
'; $form['#suffix'] = '
'; } } } function product_purchased($nid) { $arr = array(); global $user; $arr = views_get_view_result('client_orders','order_page'); foreach ($arr as $orderarr) { $order = commerce_order_load($orderarr->commerce_order_order_number); $cur_nod = node_load($nid); $prod_id = $cur_nod->field_product['und'][0]['product_id']; foreach( $order->commerce_line_items['und'] as $line_items) { $line_item = commerce_line_item_load($line_items['line_item_id']); $products = $line_item->commerce_product['und']; foreach ($products as $product_key => $product_value) { // get node id from product id if($product_value['product_id'] == $prod_id) { return true; } } } } return false; }

Share this post

Leave a comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.