I have an observer I am making that detects when someone reorders a discontinued product and should replace that product with a new product.
My question is: How do I retrieve a product object with a specific SKU? For example I want to retrieve the product with the SKU 'D1105' and add that to the cart using '$observer->getEvent()->setProduct( $myDD1105Product );'.
Here is my code almost complete. I just need to know how to retrieve a product with the SKU 'D1105' and add it to the cart. Any advice would be greatly appreciated.
<?php class MHT_Reorder_Model_Observer { public function onReorder(Varien_Event_Observer $observer) { $event = $observer->getEvent(); $product = $event->getProduct(); $replacementSku = 'D1105'; $blackListSKUs = ['D1100', 'D1101']; foreach ($blackListSKUs as $blacklistSku) { // if product SKU does not equal $blacklistSku: continue iterating if (strcasecmp($product->getSku(), $blacklistSku) != 0) continue; // How do I get the product from Mage/database that has the sku D1105? $event->setProduct() break; } } }
@sazr which event you are using.
Hi
I am using checkout_cart_product_add_after
To remove the discontinued product
$itemId = $event->getQuoteItem()->getId(); Mage::getModel('checkout/cart')->removeItem($itemId);
To get the product with SKU and add the product to cart
$newProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$yoursku); Mage::getModel('checkout/cart')->addProduct($newProduct);
Please note that people usually do not appreciate the sitation when after adding something to the cart they discover that something else has been put there. At best it's confusing and at worst it feels like hoodwinking. Both are bad.
I strongly recommend either let you customer know what you just did (like pushing an info message to the message queue) or better yet instead of doing it let customer put right product to the cart herself: on discontinued product page state that this product has been discontinued and let customer know that there's a replacement available (ideally with appropriate add to cart button). This way you're both transparent and respectful.