Friday, June 26, 2015

Drupal commerce programmatically change the quantity of product in a cart by using product id

Programmatically change the quantity of product in a cart by using product id


function product_alter_quanity($product_id, $quantity, $param) {
  $line_item_id = product_in_cart($product_id); // product_in_cart() function - http://php-developer-informations.blogspot.co.uk/2015/06/drupal-commerce-add-line-item-delete.html
  if ($line_item_id != -1 && $line_item_id != -2) {
    if ($param == 'remove') {
      $product_quantity_in_cart = commerce_line_items_quantity(array($line_item_id));
      if ($quantity >= $product_quantity_in_cart) {
        product_delete_cart($product_id);
      }
      else {
        $line_item = commerce_line_item_load($line_item_id);
        $line_item->quantity = $line_item->quantity - $quantity;
        commerce_line_item_save($line_item);
      }
    }
    elseif ($param == 'add') {
      //$line_item_id = product_in_cart($product_id);
      $line_item = commerce_line_item_load($line_item_id);
      $line_item->quantity = $line_item->quantity + $quantity;
      commerce_line_item_save($line_item);
    }
  }
  else {
    return -1;
  }
}

No comments:

Post a Comment