How to Delete Order Item from Order Object in Magento

ordersvarien

How to delete order item from order object? For example:

$order = Mage::getModel('sales/order')->load(1);

foreach($order->getAllItems() as $item) {
    $order->removeByItemId($item->getId());
}

Best Answer

This is more of a hack. Warning: you could accidentally delete items if you're not careful.

The getAllItems method filters items out of the item collection and returns it. In order to filter items out of the getAllItems array you simply need to mark the desired items in the collection as deleted:

foreach($order->getAllItems() as $item) {
    $item->isDeleted(true);
}

Subsequent calls to getAllItems will return items not marked as deleted.

Now, where things get hairy is that if you call save on that item, it will delete it. This is dangerous.

So, what I suggest instead, is that you build your own collection with only the data that you know that you want. For instance:

$collection = new Varien_Data_Collection();

And then populate it:

foreach($order->getAllItems() as $item) {
    //some condition
    $collection->addItem($item);
}

Now your new collection only contains the data that you want, and you can hand that around.

Related Topic