You are here:

Magento rule conditions

Magento owns special filter for choosing products or order for promotions called rule conditions. In this post, we will learn types of rule conditions.

  1. Catalog price rules and shopping cart price rules

There are two types of promotions supported in Magento like Catalog price rules and shopping cart price rules.

  • Catalog price rules are used to products before they are added to shopping cart. Then, sales and discounts are created by these rules, which helps customer skip add a discount code.
  • Shopping cart price rules are used when having a customer visit the shopping cart page. Moreover, when setup the condition, a coupon code can be associated with a shopping cart price rules to use a discount.

Catalog rule condition is applied to create filter for products in Magento, Shopping Cart rule condition is used to create filter for order.

  1. Create database and model for custom rule conditions

We will cover that way to create a module for shopping cart rule conditions.

In this example, we will create module “example” and customize for this module in file appcodelocalMagentoexamplesqlexample_setupmysql4-install-0.1.0.php:

CREATE TABLE {$this->getTable(‘example’)} (

example_id int(11) unsigned NOT NULL auto_increment,

name VARCHAR(255) NULL,

description TEXT NULL,

is_active SMALLINT(6) NULL,

website_ids TEXT NULL,

customer_group_ids TEXT NULL,

from_date DATETIME NULL,

to_date DATETIME NULL,

sort_order INT(11) NULL,

conditions_serialized MEDIUMTEXT NULL,

actions_serialized MEDIUMTEXT NULL,

custom_discount DECIMAL(12,4) NULL,

PRIMARY KEY (example_id)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You need to pay attention to special some fields of this table to store data of conditions:

  • conditions_serialized: save data of shopping cart conditions in serialized form
  • actions_serialized: save data of shopping cart item conditions in string serialized form

After that, you need to customize in model you wrote.

We support a model below:

class Magento_example_Model_example extends Mage_Rule_Model_Rule {public function _construct(){parent::_construct();$this->_init(‘example/ example ‘);$this->setIdFieldName(‘ example _id’);} public function getConditionsInstance(){return Mage::getModel(‘salesrule/rule_condition_combine’);} public function getActionsInstance(){return Mage::getModel(‘salesrule/rule_condition_product_combine’);} /*** load Rule posted from web** @param array $rule* @return Magento_RewardPointsRule_Model_Earning_Sales*/public function loadPost(array $rule){$arr = $this->_convertFlatToRecursive($rule);if (isset($arr[‘conditions’])) {$this->getConditions()->setConditions(array())->loadArray($arr[‘conditions’][1]);}if (isset($arr[‘actions’])) {$this->getActions()->setActions(array())->loadArray($arr[‘actions’][1], ‘actions’);}return $this;} protected function _beforeSave(){parent::_beforeSave();if ($this->hasWebsiteIds()) {$websiteIds = $this->getWebsiteIds();if (is_array($websiteIds) && !empty($websiteIds)) {$this->setWebsiteIds(implode(‘,’, $websiteIds));}}if ($this->hasCustomerGroupIds()) {$groupIds = $this->getCustomerGroupIds();if (is_array($groupIds) && !empty($groupIds)) {$this->setCustomerGroupIds(implode(‘,’, $groupIds));}}return $this;}}

  1. Rule conditions edit form

After creating module, you need to create admin pages in backend.

Use conditions template for tab conditions. In this example, we write in _prepareForm method of file app\code\local\Magento\example\Block\Adminhtml\example\Edit\Tab\Conditions.php

$form = new Varien_Data_Form(); $form->setHtmlIdPrefix(‘rule_’); $renderer = Mage::getBlockSingleton(‘adminhtml/widget_form_renderer_fieldset’)->setTemplate(‘promo/fieldset.phtml’)->setNewChildUrl($this-   >getUrl(‘adminhtml/promo_quote/newConditionHtml/form/rule_conditions_fieldset’)); $fieldset = $form->addFieldset(‘conditions_fieldset’, array(‘legend’=>Mage::helper(‘example’)->__(‘Apply the rule only if the following conditions are met (leave blank for all order)’)))->setRenderer($renderer); $fieldset->addField(‘conditions’,’text’,array(‘name’ => ‘conditions’,‘label’ => Mage::helper(‘lesson28′)->__(‘Conditions’),‘title’ => Mage::helper(‘lesson28′)->__(‘Conditions’),‘required’ => true,))->setRule($model)->setRenderer(Mage::getBlockSingleton(‘rule/conditions’));

Enter load JS to edit form from controllers

app\code\local\Magento\example\controllers\Adminhtml\exampleController.php

Follow method below:

public function editAction() {$exampleId = $this->getRequest()->getParam(‘id’);$model = Mage::getModel(‘example/example’)->load($exampleId); if ($model->getId() || $exampleId == 0) {$data = Mage::getSingleton(‘adminhtml/session’)->getFormData(true);if (!empty($data)) {$model->setData($data);} $model->getConditions()->setJsFormObject(‘rule_conditions_fieldset’);$model->getActions()->setJsFormObject(‘rule_actions_fieldset’); Mage::register(‘example_data’, $model); $this->loadLayout();$this->_setActiveMenu(‘example/example’); $this->getLayout()->getBlock(‘head’)->setCanLoadExtJs(true)->setCanLoadRulesJs(true);$this->_addContent($this->getLayout()->createBlock(‘lesson28/adminhtml_example _edit’))->_addLeft($this->getLayout()->createBlock(‘lesson28/adminhtml_example _edit_tabs’)); $this->renderLayout();} else {Mage::getSingleton(‘adminhtml/session’)->addError(Mage::helper(‘lesson28′)->__(‘Item does not exist’));$this->_redirect(‘*/*/’);}}

Add shopping cart items conditions to form by customizing in file

app\code\local\Magento\example\Block\Adminhtml\example\Edit\Tab\Actions.php in method _prepareForm like conditions tab:

$form = new Varien_Data_Form(); $form->setHtmlIdPrefix(‘rule_’);$this->setForm($form);$fieldset = $form->addFieldset(‘discount_action_fieldset’, array(‘legend’ => Mage::helper(‘example’)->__(‘Action’))); $fieldset->addField(‘custom_discount’, ‘text’, array(‘label’ => Mage::helper(‘example’)->__(‘Custom Discount’),‘title’ => Mage::helper(‘example’)->__(‘Custom Discount’),‘name’ => ‘custom_discount’,‘after_element_html’ => ‘<strong>[‘ . Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE) . ‘]</strong>’,)); $renderer = Mage::getBlockSingleton(‘adminhtml/widget_form_renderer_fieldset’)->setTemplate(‘promo/fieldset.phtml’)->setNewChildUrl($this->getUrl(‘adminhtml/promo_quote/newActionHtml/form/rule_actions_fieldset’)); $fieldset = $form->addFieldset(‘actions_fieldset’, array(‘legend’ => Mage::helper(‘example’)->__(‘Apply the rule only to cart items matching the following conditions (leave blank for all items)’)))->setRenderer($renderer); $fieldset->addField(‘actions’, ‘text’, array(‘label’ => Mage::helper(‘example’)->__(‘Apply To’),‘title’ => Mage::helper(‘example’)->__(‘Apply To’),‘name’ => ‘actions’,))->setRule($model)->setRenderer(Mage::getBlockSingleton(‘rule/actions’));

Enter following code to save action:

$model->loadPost($data) ->setData(‘from_date’,$data[‘from_date’])->setData(‘to_date’,$data[‘to_date’])->save();

  1. Validate rule conditions

Checking actions for shopping cart is final step.

For example, we will create a custom total but discount value taken from table of this module.

Collect total detail of model (Magento_example_Model_Total_Quote_Discount)

public function collect(Mage_Sales_Model_Quote_Address $address) {$quote = $address->getQuote();if (!$quote->isVirtual() && $address->getAddressType() == ‘billing’) {return $this;} // Get Rules Discount$rules = Mage::getResourceModel(‘example/ example _collection’)->setAvailableFilter($quote->getCustomerGroupId(), Mage::app()->getWebsite()->getId());foreach ($rules as $rule) {if ($rule->validate($address)) {$itemBaseDiscount = $rule->getCustomDiscount();break;}} $itemDiscount = Mage::app()->getStore()->convertPrice($itemBaseDiscount);$totalDiscount = 0;$baseTotalDiscount = 0;foreach ($address->getAllItems() as $item) {if ($item->getParentItemId()) continue;if (!$rule->getActions()->validate($item)) {continue;}if ($item->getHasChildren() && $item->isChildrenCalculated()) {foreach ($item->getChildren() as $child) {$totalDiscount += $itemDiscount;$baseTotalDiscount += $itemBaseDiscount; $child->setBaseCustomDiscount($itemBaseDiscount);$child->setCustomDiscount($itemDiscount);}} else {$totalDiscount += $itemDiscount;$baseTotalDiscount += $itemBaseDiscount; $item->setBaseCustomDiscount($itemBaseDiscount);$item->setCustomDiscount($itemDiscount);}} if ($totalDiscount > 0) {$address->setCustomDiscount($totalDiscount);$address->setBaseCustomDiscount($baseTotalDiscount); $address->setGrandTotal($address->getGrandTotal() – $totalDiscount)->setBaseGrandTotal($address->getBaseGrandTotal() – $baseTotalDiscount);} return $this;}

Done! We’ve determined all about Magento rule conditions. However, if you want to totally understand this tutorial, you need to have background of rule conditions and the way to use them. So, if you have any questions, ask us for help.

Thanks for reading!

Related articles
 

404

Back to Top