Showing posts with label Find line item. Show all posts
Showing posts with label Find line item. Show all posts

Friday, June 26, 2015

Drupal Commerce find the line item id by using product id

Programmatically find the line item id by using product id


function product_in_cart($product_id) {
  if (!is_array($product_id)) {
    global $user;
    $current_order = commerce_cart_order_load($user->uid);
    if (count($current_order->commerce_line_items) > 0) {
      $line_items = $current_order->commerce_line_items;
      foreach ($line_items['und'] as $key => $value) {
        $line_item = commerce_line_item_load($value['line_item_id']);
        $products = $line_item->commerce_product['und'];
        foreach ($products as $product_key => $product_value) {
          if ($product_id == $product_value['product_id']) {
            return $value['line_item_id'];
          }
        }
      }
      return -1;
    } else
      return -2;
  }
  else {
    global $user;
    $current_order = commerce_cart_order_load($user->uid);
    if (count($current_order->commerce_line_items) > 0) {
      $line_items = $current_order->commerce_line_items;
      foreach ($line_items['und'] as $key => $value) {
        $line_item = commerce_line_item_load($value['line_item_id']);
        $products = $line_item->commerce_product['und'][0]['product_id'];
        foreach ($product_id as $id) {
          if ($id == $products) {
            $line_item_ids[] = $value['line_item_id'];
          }
        }
      } if (isset($line_item_ids) >= 1) {
        return $line_item_ids;
      }
      else {
        return -1;
      }
    } else
      return -2;
  }
}