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 Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 day ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago