創建controller_action_layout_generate_blocks_after觀察員,該方法應該是這個樣子:
注:這是主要的想法,困難的部分是解析規則,恐怕它更容易在規則說明中添加一些如: productSku:123;並且解析規則描述以查看購物車產品之一是否與規則匹配。
public function addPromotionBlock($observer)
{
$action = $observer->getEvent()->getAction();
$layout = $observer->getEvent()->getLayout();
if($action->getRequest()->getControllerName() == 'cart' && $action->getRequest()->getActionName() == 'index') {
$addPromotion = false;
$quote = Mage::getSingleton('checkout/cart')->getQuote();
$items = Mage::getSingleton('checkout/cart')->getQuote()->getAllItems();
$rules = Mage::getResourceModel('salesrule/rule_collection')
->setValidationFilter(
Mage::app()->getStore($quote->getStoreId())->getWebsiteId(),
$quote->getCustomerGroupId(),
$quote->getCouponCode())
->load();
// see Mage_SalesRule_Model_Validator
foreach ($items as $item) {
//check if the rules applies
foreach ($rules as $rule) {
var_dump($rule->toArray());
}
//let's say we found a valid rule
$addPromotion = true;
}
if ($addPromotion) {
$crosssell = $layout->getBlock('checkout.cart.crosssell');
if ($crosssell) {
//set your template here
$crosssell->setTemplate('checkout/promotion.phtml');
}
}
}
}