How to duplicate a line item in shopping cart programmatically At certain point in the checkout process I'd like to seperate line items with quantity more than one into individual line items with quantity 1.

So for example if I have a line item in cart with quantity 5, I'd like to create 4 new line items just like the original one, add them to the cart with quantity 1 individually.

I tried cloning the line item entity into a new variable and use commerce_line_item_save() with it, but it doesn't work.

Does anybody know how to achieve something like this from a module?

Thank you!
You can clone a line item and save it without any problems:

$cloned_line_item = clone($line_item);


But if what you want is to add it back to the order, you'll probably want to call commerce_cart_product_add to add your line item back to your order:

commerce_cart_product_add($uid, $line_item, FALSE);


Be careful with setting the combine options correctly if you don't want your line items to be aggregated.

$line_item-&gt;data['context']['add_to_cart_combine']


Update: Adding more details on the combine part.

In case you don't want to combine any line items for that product type:

Be aware that the combine options are at formatter level for the add to cart button, so you need to set them everywhere you're using this formatter, in manage display settings for all your view modes, in views... the configuration is not shared. This is very important as there might be hidden places you forgot to configure (if I had a penny every time I forget to configure this in "Teaser", i.e....)

In case you want to combine some times and others not:

The function commerce_cart_product_add above has a combine parameter to make Drupal Commerce try to combine or not and add a new element to the cart or just increase the quantity of an existing one.
On top of that, there's something called comparison properties, by default these are all the fields that the line item has:

foreach (field_info_instances('commerce_line_item', $line_item-&gt;type) as $info) {
  if (!empty($info['commerce_cart_settings']['field_access'])) {
    $comparison_properties[] = $info['field_name'];
  }
}


So one way you've got to hook into this process is hook_commerce_cart_product_comparison_properties_alter to define more comparison properties.