Last active
January 2, 2017 10:45
-
-
Save 0-Sony/19d7c1100372a6d02f9525344c813052 to your computer and use it in GitHub Desktop.
Magento 1 : Use Event to add product to cart and change the Quote Item Price.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| Class MyNameSpace_MyModule_Model_Observer extends Mage_Checkout_Model_Observer_Abstract { | |
| /** | |
| * Add product to cart or update product price | |
| * | |
| * @event sales_quote_collect_totals_before | |
| * @param Varien_Event_Observer $observer | |
| **/ | |
| public function updateProductPrice(Varien_Event_Observer $observer){ | |
| $quote = $observer->getEvent()->getQuote(); | |
| $mySku = 'my_sku_product'; | |
| /** @var Mage_Sales_Model_Quote_Item $item */ | |
| foreach($quote->getAllItems() as $item){ | |
| if($item->getSku() == $mySku){ | |
| Mage::register('quoteHasAlreadyOurCustomProduct', true); | |
| $product = $item->getProduct(); | |
| /** | |
| * Here We reload the product to set our customs Datas. | |
| * @var Mage_Catalog_Model_Product $product | |
| **/ | |
| $product = Mage::getModel('catalog/product')->load($product->getId()); | |
| /** 0 for Free **/ | |
| $myCustomPrice = 0; | |
| /** Tax class Id 0 in order to don't apply any Tax **/ | |
| $myCustomTaxClassId = 0; | |
| $product->setName('My Custom Name'); | |
| $product->setBasePrice($myCustomPrice); | |
| $product->setPrice($myCustomPrice); | |
| $product->setTaxClassId($myCustomTaxClassId); | |
| $item->setProduct($product); | |
| } | |
| } | |
| /** | |
| * Add our custom product to the cart | |
| **/ | |
| if(!Mage::registry('quoteHasAlreadyOurCustomProduct')){ | |
| $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $warrantyProductSku); | |
| /** | |
| * Here we can't use $product directly because its not a real instance of Mage_Catalog_Model_Product when we loaBbyAttribute | |
| **/ | |
| $quote->addProduct(Mage::getModel('catalog/product')->load($product->getId())); | |
| } | |
| $quote->save(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment