How To

How to Create Condition Rule In Magento admin Form

Magento custom module development is a core part of any Magento development project because it helps to fulfill business needs by adding custom functionality to Magento store using a module. Magento contains so many built-in features some of which you will probably never know which makes it stand out from the list of CMS’s. Magento owns special filter for choosing products or order for promotions called rule conditions. It offers types of conditions, one is catalog rule condition used to create a filter for products in Magento and other is shopping cart rule condition to create a filter for orders.

Recently while working with one of the Magento custom development projects, we came across the requirement of adding shopping cart rules to admin form to give a personalized touch by satisfying client needs. Shopping cart price rules help to create an action for orders at the checkout level, based on a set of conditions.

Firstly, we need to create ‘rules.php’ file along with the following code at below location that contains set of defined rules.

app\code\local\Vendor\Extension\Model\Rules.php

class Vendor_Extension_Model_Rules extends Mage_Rule_Model_Rule
{
         protected function _construct() {
          $this->_init('extension/extension');
          $this->setIdFieldName('rule_id');
         }
         public function getConditionsInstance()
         {
         return Mage::getModel('catalogrule/rule_condition_combine');
         }
}

After that, we need to create another file ‘Conditions.php’ at following path that helps to create admin form in custom extension.

app\code\local\Vendor\Extension\Block\Adminhtml\Extension\Edit\Tab\Conditions.php

class Vendor_Extension_Block_Adminhtml_Extension_Edit_Tab_Conditions extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
          $model = Mage::registry('extension_data');
          $form = new Varien_Data_Form();
          $form->setHtmlIdPrefix('rule_');
         
           $renderer = Mage::getBlockSingleton('adminhtml/widget_form_renderer_fieldset')
           ->setTemplate('promo/fieldset.phtml')
           ->setNewChildUrl($this->getUrl('*/extension/newConditionHtml/form/rule_conditions_fieldset'));
         
          $fieldset = $form->addFieldset('conditions_fieldset', array('legend'=>Mage::helper('extension')->__('Apply the rule only if the following conditions are met (leave blank for all item)')))->setRenderer($renderer);
    
          $fieldset->addField('conditions','text',array(
          'name' => 'conditions',
          'label' => Mage::helper('extension')->__('Conditions'),
          'title' => Mage::helper('extension')->__('Conditions'),
          'required' => true,
          ))->setRule($model)->setRenderer(Mage::getBlockSingleton('rule/conditions'));
         
          $form->setValues($model->getData());
          $this->setForm($form);
          return parent::_prepareForm();
    }
}

Lastly, we need to create ‘ExtensionController.php’ at below location to create multiple actions and control activities.

 app\code\local\Vendor\Extension\controllers\Adminhtml\ExtensionController.php

class Vendor_Extension_Adminhtml_ExtensionController extends Mage_Adminhtml_Controller_Action
{
    public function editAction()
    {
          $testId = $this->getRequest()->getParam('id');
          $testModel = Mage::getModel('extension/rules')->load($testId);
          if ($testModel->getRuleId() || $testId == 0)
                       {
                       Mage::register('extension_data', $testModel);
                       $this->loadLayout();
                       $this->_setActiveMenu('extension');
                       $this->getLayout()->getBlock('head')
                                                          ->setCanLoadExtJs(true)
                                                          ->setCanLoadRulesJs(true);
                                $this->_addContent($this->getLayout()
                                                        ->createBlock('extension/adminhtml_extension_edit'))
                                               ->_addLeft($this->getLayout()
                                                        ->createBlock('extension/adminhtml_extension_edit_tabs')
                                    );
 
                                   $this->renderLayout();
                                   }
              else
              {
                                Mage::getSingleton('adminhtml/session')->addError('model does not exist');
                                $this->_redirect('*/*/');
                                }
          }
    public function newConditionHtmlAction()
    {
            $id = $this->getRequest()->getParam('id');
            $typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type')));
            $type = $typeArr[0];
            $model = Mage::getModel($type)
                                                ->setId($id)
                                                ->setType($type)
                                                ->setRule(Mage::getModel('catalogrule/rule'))
                                                ->setPrefix('conditions');
            if (!empty($typeArr[1])) {
                      $model->setAttribute($typeArr[1]);
            }
                      if ($model instanceof Mage_Rule_Model_Condition_Abstract) {
                      $model->setJsFormObject($this->getRequest()->getParam('form'));
                      $html = $model->asHtmlRecursive();
            } else {
                      $html = '';
      }
    $this->getResponse()->setBody($html);
  }
 
}

Once you have added this code to your extension, you are done. It will start displaying rules in backend admin form.

Not only this you can even customize this code as per your need.

Lastly, Comment down below if you need any help regarding this code.

Happy Coding!

Click to rate this post!
[Total: 4 Average: 3]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

2 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

4 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

5 days ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

5 days ago

8 Best Social Login Apps for Shopify Store in 2024

Running an eCommerce business can be incredibly demanding, leaving entrepreneurs little time to focus on…

5 days ago

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

6 days ago