Remove an item from admin order quote and add new item programmatically
-
13-12-2019 - |
Question
I am working on a project that needs to tweak admin order creation function of magento.
I need to remove an item and then add another item programmatically while creating order.
For example, few items are already added to order, now if product id matches with my_product_id
, remove that product from quote
and add new product (my_new_product
) to order.
It will not be from observer
, since I will need to add a button to call this action and do the job.
I have successfully added a button and linked to my custom controller.
I have gone through loads of links, but no luck.
Please suggest.
Solution 2
After digging up for few days, I have been able to get the result.
A big thanks to @lloiacono for pointing me to right direction, however his/her answer wasn't good enough.
In my controller file:
public function removeAndAddAction()
{
$quote = $this->_getSession()->getQuote();
foreach($quote->getAllItems() as $item){
$quote->removeItem($item->getId());
$product = Mage::getModel('catalog/product')->load($item->getProductId());
$quote->addProduct($product, 1);
}
$quote->collectTotals()->save();
$this->_redirect('*/sales_order_create');
}
//get session
protected function _getSession()
{
$session = Mage::getSingleton('adminhtml/session_quote');
return $session;
}
OTHER TIPS
Update
Since you only need to tweak the existing admin order creation you could hook to: sales_order_save_before or adminhtml_sales_order_create_process_data but make sure you add this in to the <adminhtml>
node in your config.xml
.
Once in your Observer.php you can remove the items you wish, I would instead try to hook to a quote event also in the <adminhtml>
node and then remove the item at a quote level if possible.
To add an item to the quote:
$quote->addProduct($product, new Varien_Object($eventArgs));
$quote->save();
To remove an item from the quote:
$quote->removeItem($item->getItemId())->save();
Then you can have magento create the admin order:
$adminSalesOrderCreate = Mage::getSingleton('adminhtml/sales_order_create');
$adminSalesOrderCreate->setQuote($quote)->save();
There is a very complete answer here: https://magento.stackexchange.com/a/15050/5913