how to apply catalog price rules in magento by observer?
Question
i need to create price rule by programmatically with help of Observer
and i want to know that which event call for this
Solution
you can do this by event checkout_cart_product_add_after:
You need create config.xml for like below:
<events>
<checkout_cart_product_add_after>
<observers>
<create_own_catalog_price_rules>
<type>singleton</type>
<class>yourmodel/observer</class>
<method>updatePrice</method>
</create_own_catalog_price_rules>
</observers>
</create_own_catalog_price_rules>
</events>
And Observer.php code of create catalog price:
public function updatePrice( Varien_Event_Observer $obs )
{
$quote = $obs->getEvent()->getQuote();
$item = $obs->getQuoteItem();
$product_id=$item->getProduct_id();
$_product=Mage::getModel('catalog/product')->load($product_id);
$name = "My Catalog Price Rule"; // name of Catalog Price Rule
$websiteId = 1;
$customerGroupId = 2;
$actionType = 'to_fixed'; // discount to fixed amount
//(other options are: by_fixed, by_percent, to_percent)
$discount = 20; // discount amount
$sku = $_product->getSku(); // product sku
$catalogPriceRule = Mage::getModel('catalogrule/rule');
$catalogPriceRule->setName($name)
->setDescription('')
->setIsActive(1)
->setWebsiteIds(array($websiteId))
->setCustomerGroupIds(array($customerGroupId))
->setFromDate('')
->setToDate('')
->setSortOrder('')
->setSimpleAction($actionType)
->setDiscountAmount($discount)
->setStopRulesProcessing(0);
$skuCondition = Mage::getModel('catalogrule/rule_condition_product')
->setType('catalogrule/rule_condition_product')
->setAttribute('sku')
->setOperator('==')
->setValue($sku);
try {
$catalogPriceRule->getConditions()->addCondition($skuCondition);
$catalogPriceRule->save();
$catalogPriceRule->applyAll();
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError(Mage::helper('catalog')->__($e->getMessage()));
return;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange