#StackBounty: #drupal-commerce How to add a new line item to existing recurring order?

Bounty: 50

I’ve managed to get new line items added to a recurring order using hook_commerce_license_billing_order_refresh_alter() and the code is:

$product = commerce_product_load_by_sku($sku);
$li = commerce_product_line_item_new($product, '1');
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_needs_save = TRUE;
commerce_line_item_save($li);
$line_items[$li->line_item_id] = $li;

It adds line items and correctly calculates new total and shows on the recurring order page. However, since this is a fresh hook it keeps creating new products, line items and licenses on every refresh. So I tried to attach already created line items with adding to the order’s data array:

// Add line item objects to order data.
$order->data['lis'][] = $li;
// Add sku to order data.
$order->data['skus'][] = $sku;

and then re-use it with:

if (!empty($order->data['lis'])) {
        foreach ($order->data['lis'] as $key => $li) {
          $wrapper = entity_metadata_wrapper('commerce_order', $order);
          $order_needs_save = TRUE;
          $line_items[$li->line_item_id] = $li;
        }
      }

but, unfortunately, the new line items do not show on the recurring order. If I add commerce_line_item_save($li); line, then the website crashes giving:

EntityMetadataWrapperException: Unable to get the data property line_item_id as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 457 of /home/username/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).

So my question is: how I should properly add new line items to existing recurring order?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.