2

Magento 2 custom extension how to put a rule condition into the custom admin form using the ui component with data base interaction.

please refer the following rule condition image

enter image description here

4
  • have you got any solution? i want to also implement same functionality using UI component. Jan 3, 2019 at 6:25
  • No i am not get Jan 4, 2019 at 9:57
  • have you got any solution? Oct 22, 2019 at 11:09
  • No, I don't get any solution Oct 23, 2019 at 8:56

5 Answers 5

1

Click Here For Part 2

After adding above files you can see condition field into your form

In above section we create admin grid and form. In custom_condition_form.xml form file at app/code/VendoreName/AddConditionFiled/view/adminhtml/ui_component uncomment below code:

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">custom_condition_form.custom_condition_listing_data_source</item>
            <item name="deps" xsi:type="string">custom_condition_form.custom_condition_listing_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">General Information</item>
        <item name="config" xsi:type="array">
            <item name="dataScope" xsi:type="string">data</item>
            <item name="namespace" xsi:type="string">custom_condition_form</item>
        </item>
        <item name="spinner" xsi:type="string">general_information</item>
        <item name="buttons" xsi:type="array">
            <item name="back" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Back</item>
            <item name="delete" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Delete</item>
            <item name="reset" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Reset</item>
            <item name="save" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Save</item>
        </item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
    </argument>
    ............................................................................................................

Step-19: Create Generic.php at app/code/VendoreName/AddConditionFiled/Block/Adminhtml/Edit/Button

<?php

namespace VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button;

use Magento\Backend\Block\Widget\Context;
use Magento\Cms\Api\PageRepositoryInterface;

class Generic
{
    protected $context;
    protected $pageRepository;

    public function __construct(
        Context $context,
        PageRepositoryInterface $pageRepository
    ) {
        $this->context = $context;
        $this->pageRepository = $pageRepository;
    }

    public function getUrl($route = '', $params = [])
    {
        return $this->context->getUrlBuilder()->getUrl($route, $params);
    }
}

Step-20: Create Back.php at app/code/VendoreName/AddConditionFiled/Block/Adminhtml/Edit/Button

<?php

namespace VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

class Back extends Generic implements ButtonProviderInterface
{
    public function getButtonData()
    {
        return [
            'label' => __('Back'),
            'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
            'class' => 'back',
            'sort_order' => 10,
        ];
    }

    public function getBackUrl()
    {
        return $this->getUrl('*/*/');
    }
}

Step-21: Create Reset.php at app/code/VendoreName/AddConditionFiled/Block/Adminhtml/Edit/Button

<?php

namespace VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

class Reset implements ButtonProviderInterface
{
    public function getButtonData()
    {
        return [
            'label' => __('Reset'),
            'class' => 'reset',
            'on_click' => 'location.reload();',
            'sort_order' => 30,
        ];
    }
}

Step-22: Create Delete.php at app/code/VendoreName/AddConditionFiled/Block/Adminhtml/Edit/Button

<?php

namespace VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button;

use Magento\Backend\Block\Widget\Context;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

class Delete extends Generic implements ButtonProviderInterface
{
    protected $context;

    public function __construct(
        Context $context
    ) {
        $this->context = $context;
    }

    public function getButtonData()
    {
        $data = [];
        $rule_id = $this->context->getRequest()->getParam('rule_id');
        if ($rule_id) {
            $data = [
                'label' => __('Delete'),
                'class' => 'delete',
                'on_click' => 'deleteConfirm(\'' . __(
                    'Are you sure you want to delete this?'
                ) . '\', \'' . $this->getDeleteUrl() . '\')',
                'sort_order' => 20,
            ];
        }
        return $data;
    }

    public function getDeleteUrl()
    {
        $rule_id = $this->context->getRequest()->getParam('rule_id');
        return $this->getUrl('*/*/delete', ['rule_id' => $rule_id]);
    }
}

Step-23: Create Save.php at app/code/VendoreName/AddConditionFiled/Block/Adminhtml/Edit/Button

<?php

namespace VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
use Magento\Ui\Component\Control\Container;

class Save extends Generic implements ButtonProviderInterface
{
    public function getButtonData()
    {
        return [
            'label' => __('Save'),
            'class' => 'save primary',
            'data_attribute' => [
                'mage-init' => [
                    'buttonAdapter' => [
                        'actions' => [
                            [
                                'targetName' => 'custom_condition_form.custom_condition_form',
                                'actionName' => 'save',
                                'params' => [
                                    false,
                                ],
                            ],
                        ],
                    ],
                ],
            ],
            'class_name' => Container::SPLIT_BUTTON,
            'options' => $this->getOptions(),
        ];
    }

    protected function getOptions()
    {
        $options[] = [
            'id_hard' => 'save_and_new',
            'label' => __('Save & New'),
            'data_attribute' => [
                'mage-init' => [
                    'buttonAdapter' => [
                        'actions' => [
                            [
                                'targetName' => 'custom_condition_form.custom_condition_form',
                                'actionName' => 'save',
                                'params' => [
                                    true,
                                    [
                                        'back' => 'add',
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ];
        $options[] = [
            'id_hard' => 'save_and_close',
            'label' => __('Save & Close'),
            'data_attribute' => [
                'mage-init' => [
                    'buttonAdapter' => [
                        'actions' => [
                            [
                                'targetName' => 'custom_condition_form.custom_condition_form',
                                'actionName' => 'save',
                                'params' => [
                                    true,
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ];
        return $options;
    }
}

After We Creating controller action file form perform CRUD operation.

Step-24: Create Rule.php at app/code/VendoreName/AddConditionFiled/Controller/Adminhtml/Index

<?php

namespace VendoreName\AddConditionFiled\Controller\Adminhtml\Index;

abstract class Rule extends \Magento\Backend\App\Action
{
    protected $coreRegistry = null;
    protected $fileFactory;
    protected $dateFilter;
    protected $ruleFactory;
    protected $logger;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter,
        \VendoreName\AddConditionFiled\Model\CustomConditionFactory $ruleFactory,
        \Psr\Log\LoggerInterface $logger
    ) {
        parent::__construct($context);
        $this->coreRegistry = $coreRegistry;
        $this->fileFactory = $fileFactory;
        $this->dateFilter = $dateFilter;
        $this->ruleFactory = $ruleFactory;
        $this->logger = $logger;
    }

    protected function _initRule()
    {
        $rule = $this->ruleFactory->create();
        $this->coreRegistry->register(
            'current_rule',
            $rule
        );
        $id = (int) $this->getRequest()->getParam('id');

        if (!$id && $this->getRequest()->getParam('rule_id')) {
            $id = (int) $this->getRequest()->getParam('rule_id');
        }

        if ($id) {
            $this->coreRegistry->registry('current_rule')->load($id);
        }
    }

    protected function _initAction()
    {
        $this->_view->loadLayout();
        return $this;
    }

}

Step-25: Create NewActionHtml.php at app/code/VendoreName/AddConditionFiled/Controller/Adminhtml/Index

<?php

namespace VendoreName\AddConditionFiled\Controller\Adminhtml\Index;

class NewActionHtml extends \VendoreName\AddConditionFiled\Controller\Adminhtml\Index\Rule
{
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        $typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type')));
        $type = $typeArr[0];

        $model = $this->_objectManager->create(
            $type
        )->setId(
            $id
        )->setType(
            $type
        )->setRule(
            $this->ruleFactory->create()
        )->setPrefix(
            'actions'
        );
        if (!empty($typeArr[1])) {
            $model->setAttribute($typeArr[1]);
        }

        if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) {
            $model->setJsFormObject("custom_condition_form");
            $model->setFormName("custom_condition_form");
            $html = $model->asHtmlRecursive();
        } else {
            $html = '';
        }
        $this->getResponse()->setBody($html);
    }
}

Step-26: Create Delete.php at app/code/VendoreName/AddConditionFiled/Controller/Adminhtml/Index

<?php

namespace VendoreName\AddConditionFiled\Controller\Adminhtml\Index;

use Magento\Backend\App\Action;

class Delete extends Action
{
    protected $customConditionModel;

    public function __construct(
        Action\Context $context,
        \VendoreName\AddConditionFiled\Model\CustomConditionFactory $customConditionModel
    ) {
        parent::__construct($context);
        $this->customConditionModel = $customConditionModel;
    }

    public function execute()
    {
        $id = $this->getRequest()->getParam('rule_id');
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {
                $model = $this->customConditionModel->create();
                $model->load($id);
                $model->delete();
                $this->messageManager->addSuccess(__('The rule is deleted successfully.'));
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['rule_id' => $id]);
            }
        }
        $this->messageManager->addError(__('The rule does not exist'));
        return $resultRedirect->setPath('*/*/');
    }
}

Step-27: Create Save.php at app/code/VendoreName/AddConditionFiled/Controller/Adminhtml/Index

<?php

namespace VendoreName\AddConditionFiled\Controller\Adminhtml\Index;

use VendoreName\AddConditionFiled\Model\CustomConditionFactory;
use Magento\Backend\App\Action;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Controller\ResultFactory;

class Save extends \Magento\Backend\App\Action
{

    protected $ruledatamodel;
    protected $dataPersistor;
    protected $productCollectionFactory;

    public function __construct(
        Action\Context $context,
        CollectionFactory $productCollectionFactory,
        CustomConditionFactory $ruledatamodel
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->ruledatamodel = $ruledatamodel;
        parent::__construct($context);
    }

    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (isset($data['rule']['conditions'])) {
            $data['conditions'] = $data['rule']['conditions'];
        }
        if (isset($data['rule'])) {
            unset($data['rule']);
        }
        try {
            $model = $this->ruledatamodel->create();
            $id = $this->getRequest()->getParam('rule_id');
            if ($id) {
                $model->load($id);
            }
            if (!$model->getId() && $id) {
                $this->messageManager->addErrorMessage(__('This rule is no longer exists.'));
                return $resultRedirect->setPath('addconditionfiled/index/index');
            }
            $model->loadPost($data);
            $model->save();
            $this->messageManager->addSuccess(__('Rule has been successfully saved.'));
            if ($this->getRequest()->getParam('back')) {
                if ($this->getRequest()->getParam('back') == 'add') {
                    return $resultRedirect->setPath('addconditionfiled/index/add');
                } else {
                    return $resultRedirect->setPath(
                        'addconditionfiled/index/edit',
                        [
                            'rule_id' => $model->getId(),
                        ]
                    );
                }
            }
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong while saving the data.'));
            return $resultRedirect->setPath('addconditionfiled/index/add');
        }
        return $resultRedirect->setPath('addconditionfiled/index/index');
    }
}

Step-28: Create Edit.php at app/code/VendoreName/AddConditionFiled/Controller/Adminhtml/Index

<?php

namespace VendoreName\AddConditionFiled\Controller\Adminhtml\Index;

class Edit extends \Magento\Backend\App\Action
{
    protected $resultPageFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Edit Rule'));
        return $resultPage;
    }
}

Step-29: Create addconditionfiled_index_edit.xml at app/code/VendoreName/AddConditionFiled/view/adminhtml/layout

<?xml version="1.0"?>
 
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceContainer name="content">
            <uiComponent name="custom_condition_form"/>
        </referenceContainer>
    </body>
</page>

Now your Admin from and grid are ready for CRUD Operation.

Check condition with products in Magento 2

1
  • 1
    It's hardcoded a lot, but in general I used it like example. VendoreName\AddConditionFiled\Model\DataProvider this file is not provided. For people who knows what to do it will be useful. Thanks for it. I have added all code, that you wrote to the separate github repo, with some small changes that you missed. Hope it will be helpful for someone: github.com/bbakalov/AddConditionFiled_stackoverflow
    – bdn
    Aug 29, 2021 at 9:12
0

For adding condition element try to add next:

1) ui_component/your_name.xml :

<container name="display_container">
        <htmlContent name="html_content">
            <argument name="block" xsi:type="object">YourName\YourModule\Block\Adminhtml\Rule\Edit\Tab\ProductConditions</argument>
        </htmlContent>
    </container>

2) How to create condition block - look at this Magento file:

vendor/magento/module-catalog-rule/Block/Adminhtml/Promo/Catalog/Edit/Tab/Conditions.php

I hope this information will help you to add custom conditions on your form.

2
  • Hello @amasty please provide the full tutorial without the field we can not initialize into the ui component Nov 29, 2018 at 8:43
  • any answers from other developers ? Nov 29, 2018 at 11:09
0

Too late but it may help someone.In ui_component form

ui_component_form

<fieldset name="conditions">
        <settings>
            <collapsible>true</collapsible>
            <label translate="true">Conditions</label>
        </settings>
        <container name="conditions_apply_to" sortOrder="10">
            <htmlContent name="html_content">
                <block name="conditions_apply_to" class="Vendor\Module\Block\Adminhtml\Edit\Tab\Conditions" />
            </htmlContent>
        </container>
</fieldset>

Conditions.php

<?php
namespace Vendor\Module\Block\Adminhtml\Edit\Tab;

use Magento\Framework\App\ObjectManager;

class Conditions extends \Magento\Backend\Block\Widget\Form\Generic implements
    \Magento\Ui\Component\Layout\Tabs\TabInterface
{
    /**
     * Core registry
     *
     * @var \Magento\Backend\Block\Widget\Form\Renderer\Fieldset
     */
    protected $_rendererFieldset;

    /**
     * @var \Magento\Rule\Block\Conditions
     */
    protected $_conditions;

    /**
     * @var string
     */
    protected $_nameInLayout = 'conditions_apply_to';

    /**
     * @var \Magento\SalesRule\Model\RuleFactory
     */
    private $ruleFactory;

    /**
     * Constructor
     *
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Data\FormFactory $formFactory
     * @param \Magento\Rule\Block\Conditions $conditions
     * @param \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $rendererFieldset
     * @param array $data
     * @param \Magento\SalesRule\Model\RuleFactory|null $ruleFactory
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Rule\Block\Conditions $conditions,
        \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $rendererFieldset,
        array $data = [],
        \Vendor\Module\Model\RuleFactory $ruleFactory = null
    ) {
        $this->_rendererFieldset = $rendererFieldset;
        $this->_conditions = $conditions;
        $this->ruleFactory = $ruleFactory ?: ObjectManager::getInstance()
            ->get(\Magento\SalesRule\Model\RuleFactory::class);
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * {@inheritdoc}
     * @codeCoverageIgnore
     */
    public function getTabClass()
    {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function getTabUrl()
    {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function isAjaxLoaded()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getTabLabel()
    {
        return __('Conditions');
    }

    /**
     * {@inheritdoc}
     */
    public function getTabTitle()
    {
        return __('Conditions');
    }

    /**
     * {@inheritdoc}
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * Prepare form before rendering HTML
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        $model = $this->_coreRegistry->registry('registry_name');
        $form = $this->addTabToForm($model);
        $this->setForm($form);

        return parent::_prepareForm();
    }

    /**
     * Handles addition of conditions tab to supplied form.
     *
     * @param \Magento\SalesRule\Model\Rule $model
     * @param string $fieldsetId
     * @param string $formName
     * @return \Magento\Framework\Data\Form
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function addTabToForm($model, $fieldsetId = 'conditions_fieldset', $formName = 'your_ui_component_form_name')
    {
        if (!$model) {
            $id = $this->getRequest()->getParam('id');
            $model = $this->ruleFactory->create();
            $model->load($id);
        }
        // $conditionsFieldSetId = $model->getConditionsFieldSetId($formName);
        $newChildUrl = $this->getUrl(
            'Admin_routes/contoller_name/newConditionHtml/form/' . $fieldsetId,
            ['form_namespace' => $formName]
        );
        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create();
        $form->setHtmlIdPrefix('rule_');
        $renderer = $this->_rendererFieldset->setTemplate(
            'Vendor_Module::promo/fieldset.phtml'
        )->setNewChildUrl(
            $newChildUrl
        )->setFieldSetId(
            $fieldsetId
        );

        $fieldset = $form->addFieldset(
            $fieldsetId,
            [
                'legend' => __(
                    'Apply the rule only if the following conditions are met (leave blank for all products).'
                )
            ]
        )->setRenderer(
            $renderer
        );
        $fieldset->addField(
            'conditions',
            'text',
            [
                'name'           => 'conditions',
                'label'          => __('Conditions'),
                'title'          => __('Conditions'),
                'required'       => true,
                'data-form-part' => $formName
            ]
        )->setRule(
            $model
        )->setRenderer(
            $this->_conditions
        );

        $form->setValues($model->getData());
        $this->setConditionFormName($model->getConditions(), $formName);
        return $form;
    }

    /**
     * Handles addition of form name to condition and its conditions.
     *
     * @param \Magento\Rule\Model\Condition\AbstractCondition $conditions
     * @param string $formName
     * @return void
     */
    private function setConditionFormName(\Magento\Rule\Model\Condition\AbstractCondition $conditions, $formName)
    {
        $conditions->setFormName($formName);
        if ($conditions->getConditions() && is_array($conditions->getConditions())) {
            foreach ($conditions->getConditions() as $condition) {
                $this->setConditionFormName($condition, $formName);
            }
        }
    }
}

newConditionHtml.php

<?php

namespace Vendor\Module\Controller\Adminhtml\controller_name;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Rule\Model\Condition\AbstractCondition;

class NewConditionHtml extends \Magento\SalesRule\Controller\Adminhtml\Promo\Quote
{
    /**
     * @return void
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        $formName = $this->getRequest()->getParam('form_namespace');
        $typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type')));
        $type = $typeArr[0];

        $model = $this->_objectManager->create($type)
            ->setId($id)
            ->setType($type)
            ->setRule($this->_objectManager->create(\Vendor\Module\Model\Rule::class))
            ->setPrefix('conditions');

        if (!empty($typeArr[1])) {
            $model->setAttribute($typeArr[1]);
        }

        if ($model instanceof AbstractCondition) {
            $model->setJsFormObject($this->getRequest()->getParam('form'));
            $model->setFormName($formName);
            $html = $model->asHtmlRecursive();
        } else {
            $html = '';
        }
        $this->getResponse()->setBody($html);
    }
}

Rule.php

<?php

namespace Vendor\Module\Model;

class Rule extends \Magento\Rule\Model\AbstractModel
{
    const STATUS_ENABLED = 1;
    const STATUS_DISABLED = 0;
    
    const CACHE_TAG = 'cache_tag';

    protected $_cacheTag = 'page_tag';

    protected $_eventPrefix = 'event_prefix';

    /** @var \Magento\SalesRule\Model\Rule\Condition\CombineFactory */
    /**
    * CMS page cache tag.
    */
    const TYPE_ID = 'id';
    const NAME = 'name';

    protected $_eventObject = 'rule';

    /** @var \Magento\SalesRule\Model\Rule\Condition\CombineFactory */
    protected $condCombineFactory;

    /** @var \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory */
    protected $condProdCombineF;

    /**
     * Store already validated addresses and validation results
     *
     * @var array
     */
    protected $validatedAddresses = [];

    /**
     * @param \Magento\Framework\Model\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Data\FormFactory $formFactory
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
     * @param \Magento\SalesRule\Model\Rule\Condition\CombineFactory $condCombineFactory
     * @param \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory $condProdCombineF
     * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
     * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
     * @param array $data
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Magento\SalesRule\Model\Rule\Condition\CombineFactory $condCombineFactory,
        \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory $condProdCombineF,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        array $data = []
    ) {
        $this->condCombineFactory = $condCombineFactory;
        $this->condProdCombineF = $condProdCombineF;
        parent::__construct($context, $registry, $formFactory, $localeDate, $resource, $resourceCollection, $data);
    }
    /**
     * Initialize resource model.
     */
    protected function _construct()
    {
        $this->_init('Vendor\Module\Model\ResourceModel\Rule');
    }
    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }

    public function getDefaultValues()
    {
        $values = [];

        return $values;
    }
    public function getAvailableStatuses()
    {
        return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')];
    }
    /**
     * Get rule condition combine model instance
     *
     * @return \Magento\SalesRule\Model\Rule\Condition\Combine
     */
    public function getConditionsInstance()
    {
        return $this->condCombineFactory->create();
    }

    /**
     * Get rule condition product combine model instance
     *
     * @return \Magento\SalesRule\Model\Rule\Condition\Product\Combine
     */
    public function getActionsInstance()
    {
        return $this->condProdCombineF->create();
    }

    /**
     * Check cached validation result for specific address
     *
     * @param Address $address
     * @return bool
     */
    public function hasIsValidForAddress($address)
    {
        $addressId = $this->_getAddressId($address);
        return isset($this->validatedAddresses[$addressId]) ? true : false;
    }

    /**
     * Set validation result for specific address to results cache
     *
     * @param Address $address
     * @param bool $validationResult
     * @return $this
     */
    public function setIsValidForAddress($address, $validationResult)
    {
        $addressId = $this->_getAddressId($address);
        $this->validatedAddresses[$addressId] = $validationResult;
        return $this;
    }

    /**
     * Get cached validation result for specific address
     *
     * @param Address $address
     * @return bool
     * @SuppressWarnings(PHPMD.BooleanGetMethodName)
     */
    public function getIsValidForAddress($address)
    {
        $addressId = $this->_getAddressId($address);
        return isset($this->validatedAddresses[$addressId]) ? $this->validatedAddresses[$addressId] : false;
    }

    /**
     * Return id for address
     *
     * @param Address $address
     * @return string
     */
    private function _getAddressId($address)
    {
        if ($address instanceof Address) {
            return $address->getId();
        }
        return $address;
    }
    

}

fieldset.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/**@var \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $block */
?>
<?php $_element = $block->getElement(); ?>
<?php $_jsObjectName = $block->getFieldSetId() != null ? $block->getFieldSetId() : $_element->getHtmlId(); ?>
<script>require([
    'jquery'
], function ($) {
    'use strict';
        $('div[data-index="conditions"]').click(function(){
        $('select[name="rule[conditions][1][new_child]"] optgroup[label="Cart Attribute"] option:nth-child(5)').css('display','none');
}); 
});</script>
<div class="rule-tree">
    <fieldset id="<?= /* @escapeNotVerified */ $_jsObjectName ?>" <?= /* @escapeNotVerified */ $_element->serialize(['class']) ?> class="fieldset">
        <legend class="legend"><span><?= /* @escapeNotVerified */ $_element->getLegend() ?></span></legend>
        <br>
    <?php if ($_element->getComment()): ?>
        <div class="messages">
            <div class="message message-notice"><?= $block->escapeHtml($_element->getComment()) ?></div>
        </div>
    <?php endif; ?>
    <div class="rule-tree-wrapper">
        <?= $_element->getChildrenHtml() ?>
    </div>
    </fieldset>
</div>
<script>
require([
    "Magento_Rule/rules",
    "prototype"
], function(VarienRulesForm){

window.<?= /* @escapeNotVerified */ $_jsObjectName ?> = new VarienRulesForm('<?= /* @escapeNotVerified */ $_jsObjectName ?>', '<?= /* @escapeNotVerified */ $block->getNewChildUrl() ?>');
<?php if ($_element->getReadonly()): ?>
    <?= $_element->getHtmlId() ?>.setReadonly(true);
<?php endif; ?>
});
</script>

0

Click Here For Part 1

Step-12: Create addconditionfiled_index_index.xml at app/code/VendoreName/AddConditionFiled/view/adminhtml/layout

<?xml version="1.0"?>
 
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceContainer name="content">
            <uiComponent name="custom_condition_listing"/>
        </referenceContainer>
    </body>
</page>

Step-13: Create custom_condition_listing.xml at app/code/VendoreName/AddConditionFiled/view/adminhtml/ui_component

<?xml version="1.0"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">custom_condition_listing.custom_condition_listing_data_source</item>
            <item name="deps" xsi:type="string">custom_condition_listing.custom_condition_listing_data_source</item>
        </item>
        <item name="spinner" xsi:type="string">custom_condition_columns</item>
        <item name="buttons" xsi:type="array">
            <item name="add" xsi:type="array">
                <item name="name" xsi:type="string">add</item>
                <item name="label" xsi:type="string" translate="true">Add New Rule</item>
                <item name="class" xsi:type="string">primary</item>
                <item name="url" xsi:type="string">*/*/add</item>
            </item>
        </item>
    </argument>
    <dataSource name="custom_condition_listing_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">VendoreNameAddConditionFiledFilterPool</argument>
            <argument name="name" xsi:type="string">custom_condition_listing_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">rule_id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
                    <item name="update_url" xsi:type="url" path="mui/index/render"/>
                    <item name="storageConfig" xsi:type="array">
                        <item name="cacheRequests" xsi:type="boolean">false</item>
                    </item>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
            </item>
        </argument>
    </dataSource>
    <container name="listing_top">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="template" xsi:type="string">ui/grid/toolbar</item>
                <item name="stickyTmpl" xsi:type="string">ui/grid/sticky/toolbar</item>
            </item>
        </argument>
        <bookmark name="bookmarks">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="namespace" xsi:type="string">custom_condition_listing</item>
                    </item>
                </item>
            </argument>
        </bookmark>
        <component name="columns_controls">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsData" xsi:type="array">
                        <item name="provider" xsi:type="string">custom_condition_listing.custom_condition_listing.custom_condition_columns</item>
                    </item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/controls/columns</item>
                    <item name="displayArea" xsi:type="string">dataGridActions</item>
                </item>
            </argument>
        </component>
        <filters name="listing_filters">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsProvider" xsi:type="string">custom_condition_listing.custom_condition_listing.custom_condition_columns</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">custom_condition_listing.custom_condition_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.filters</item>
                    </item>
                    <item name="templates" xsi:type="array">
                        <item name="filters" xsi:type="array">
                            <item name="select" xsi:type="array">
                                <item name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</item>
                                <item name="template" xsi:type="string">ui/grid/filters/elements/ui-select</item>
                            </item>
                        </item>
                    </item>
                    <item name="childDefaults" xsi:type="array">
                        <item name="provider" xsi:type="string">custom_condition_listing.custom_condition_listing.listing_top.listing_filters</item>
                        <item name="imports" xsi:type="array">
                            <item name="visible" xsi:type="string">custom_condition_listing.custom_condition_listing.custom_condition_columns.${ $.index }:visible</item>
                        </item>
                    </item>
                </item>
                <item name="observers" xsi:type="array">
                    <item name="column" xsi:type="string">column</item>
                </item>
            </argument>
        </filters>
        <paging name="listing_paging">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">custom_condition_listing.custom_condition_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.paging</item>
                    </item>
                    <item name="selectProvider" xsi:type="string">custom_condition_listing.custom_condition_listing.custom_condition_columns.ids</item>
                </item>
            </argument>
        </paging>
    </container>
    <columns name="custom_condition_columns">
        <settings>
            <childDefaults>
                <param name="fieldAction" xsi:type="array">
                    <item name="provider" xsi:type="string">custom_condition_listing.custom_condition_listing.custom_condition_columns.actions</item>
                    <item name="target" xsi:type="string">applyAction</item>
                    <item name="params" xsi:type="array">
                        <item name="0" xsi:type="string">view</item>
                        <item name="1" xsi:type="string">${ $.$data.rowIndex }</item>
                    </item>
                </param>
            </childDefaults>
        </settings>
        <selectionsColumn name="ids">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="resizeEnabled" xsi:type="boolean">false</item>
                    <item name="resizeDefaultWidth" xsi:type="string">55</item>
                    <item name="indexField" xsi:type="string">rule_id</item>
                    <item name="sortOrder" xsi:type="number">0</item>
                </item>
            </argument>
        </selectionsColumn>
        <column name="rule_id">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">textRange</item>
                    <item name="sorting" xsi:type="string">asc</item>
                    <item name="label" xsi:type="string" translate="true">Rule Id</item>
                    <item name="sortOrder" xsi:type="number">10</item>
                </item>
            </argument>
        </column>
        <column name="rule_status">
          <argument name="data" xsi:type="array">
            <item name="options" xsi:type="array">
              <item name="0" xsi:type="array">
              <item name="label" xsi:type="string">Enable</item>
              <item name="sortOrder" xsi:type="number">45</item>
              <item name="value" xsi:type="string">1</item>
            </item>
              <item name="1" xsi:type="array">
              <item name="label" xsi:type="string">Disable</item>
              <item name="value" xsi:type="string">0</item>
            </item>
            </item>
            <item name="config" xsi:type="array">
              <item name="editor" xsi:type="string">select</item>
              <item name="filter" xsi:type="string">select</item>
              <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
              <item name="dataType" xsi:type="string">select</item>
              <item name="label" xsi:type="string" translate="true">Status</item>
            </item>
          </argument>
        </column>
        <column name="rule_name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Rule Name</item>
                    <item name="sortOrder" xsi:type="number">20</item>
                    <item name="resizeEnabled" xsi:type="boolean">true</item>
                </item>
            </argument>
        </column>
        <actionsColumn name="actions" class="VendoreName\AddConditionFiled\Ui\Component\Listing\Column\AddConditionFiledActions">
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="resizeEnabled" xsi:type="boolean">false</item>
                   <item name="resizeDefaultWidth" xsi:type="string">107</item>
                   <item name="indexField" xsi:type="string">rule_id</item>
                   <item name="sortOrder" xsi:type="number">120</item>
               </item>
           </argument>
       </actionsColumn>
    </columns>
</listing>

Step-14: Create AddConditionFiledActions.php at app/code/VendoreName/AddConditionFiled/Ui/Component/Listing/Column

<?php

namespace VendoreName\AddConditionFiled\Ui\Component\Listing\Column;

class AddConditionFiledActions extends \Magento\Ui\Component\Listing\Columns\Column
{
    protected $urlBuilder;

    const URL_DELETE_PATH = 'addconditionfiled/index/delete';
    const URL_VIEW_PATH = 'addconditionfiled/index/edit';

    public function __construct(
        \Magento\Framework\UrlInterface $urlBuilder,
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        array $components = [],
        array $data = []
    ) {
        $this->urlBuilder = $urlBuilder;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$item) {
                if (isset($item['rule_id'])) {
                    $item[$this->getData('name')] = [
                        'view' => [
                            'href' => $this->urlBuilder->getUrl(
                                static::URL_VIEW_PATH,
                                [
                                    'rule_id' => $item['rule_id'],
                                ]
                            ),
                            'label' => __('Edit'),
                        ],
                        'delete' => [
                            'href' => $this->urlBuilder->getUrl(
                                static::URL_DELETE_PATH,
                                [
                                    "rule_id" => $item['rule_id'],
                                ]
                            ),
                            'label' => __('Delete'),
                            'confirm' => [
                                'title' => __('Delete'),
                                'message' => __('Are you sure you want to delete this rule ?'),
                            ],
                        ],
                    ];
                }
            }
        }
        return $dataSource;
    }
}

Step-15: Create Add.php at app/code/VendoreName/AddConditionFiled/Controller/Adminhtml/Index

<?php

namespace VendoreName\AddConditionFiled\Controller\Adminhtml\Index;

use Magento\Framework\Controller\ResultFactory;

class Add extends \Magento\Backend\App\Action
{
    public function execute()
    {
        $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
        $resultPage->getConfig()->getTitle()->prepend(__('Add New Rule'));
        return $resultPage;
    }

}

Step-16: Create addconditionfiled_index_add.xml at app/code/VendoreName/AddConditionFiled/view/adminhtml/layout

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceContainer name="content">
            <uiComponent name="custom_condition_form"/>
        </referenceContainer>
    </body>
</page>

Step-17: Create custom_condition_form.xml at app/code/VendoreName/AddConditionFiled/view/adminhtml/layout

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">custom_condition_form.custom_condition_listing_data_source</item>
            <item name="deps" xsi:type="string">custom_condition_form.custom_condition_listing_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">General Information</item>
        <item name="config" xsi:type="array">
            <item name="dataScope" xsi:type="string">data</item>
            <item name="namespace" xsi:type="string">custom_condition_form</item>
        </item>
        <item name="spinner" xsi:type="string">general_information</item>
        <!-- <item name="buttons" xsi:type="array">
            <item name="back" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Back</item>
            <item name="delete" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Delete</item>
            <item name="reset" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Reset</item>
            <item name="save" xsi:type="string">VendoreName\AddConditionFiled\Block\Adminhtml\Edit\Button\Save</item>
        </item> -->
        <item name="template" xsi:type="string">templates/form/collapsible</item>
    </argument>
    <dataSource name="custom_condition_listing_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">VendoreName\AddConditionFiled\Model\DataProvider</argument>
            <argument name="name" xsi:type="string">custom_condition_listing_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">rule_id</argument>
            <argument name="requestFieldName" xsi:type="string">rule_id</argument>
            <argument name="data" xsi:type="array">
              <item name="config" xsi:type="array">
                 <item name="submit_url" xsi:type="url" path="*/*/save"/>
              </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
    </dataSource>
    <fieldset name="rule_data">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="collapsible" xsi:type="boolean">false</item>
                <item name="label" xsi:type="string" translate="true">Rule Information</item>
                <item name="sortOrder" xsi:type="number">10</item>
            </item>
        </argument>
        <field name="rule_status">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="sortOrder" xsi:type="number">10</item>
                    <item name="dataType" xsi:type="string">boolean</item>
                    <item name="formElement" xsi:type="string">checkbox</item>
                    <item name="prefer" xsi:type="string">toggle</item>
                    <item name="label" xsi:type="string" translate="true">Enable</item>
                    <item name="valueMap" xsi:type="array">
                        <item name="true" xsi:type="number">1</item>
                        <item name="false" xsi:type="number">0</item>
                    </item>
                    <item name="valuesForOptions" xsi:type="array">
                        <item name="boolean" xsi:type="string">boolean</item>
                    </item>
                    <item name="default" xsi:type="number">1</item>
                    <item name="dataScope" xsi:type="string">rule_status</item>
                </item>
            </argument>
        </field>
        <field name="rule_name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="sortOrder" xsi:type="number">25</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Rule Name</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="source" xsi:type="string">rule_name</item>
                    <item name="dataScope" xsi:type="string">rule_name</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
    </fieldset>
    <fieldset name="condition_data">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="collapsible" xsi:type="boolean">false</item>
                <item name="label" xsi:type="string" translate="true">Condition</item>
                <item name="sortOrder" xsi:type="number">20</item>
            </item>
        </argument>
        <container name="conditions_serialized">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="sortOrder" xsi:type="number">50</item>
                </item>
            </argument>
            <htmlContent name="html_content">
                <argument name="block" xsi:type="object">VendoreName\AddConditionFiled\Block\Adminhtml\Catalog\ConditionField\Condition</argument>
            </htmlContent>
        </container>
    </fieldset>
</form>

Step-18: Create Condition.php at app/code/VendoreName/AddConditionFiled/Block/Adminhtml/Catalog/ConditionField

<?php

namespace VendoreName\AddConditionFiled\Block\Adminhtml\Catalog\ConditionField;

use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Framework\App\ObjectManager;

class Condition extends Generic implements TabInterface
{
    protected $_rendererFieldset;

    protected $_conditions;

    protected $_nameInLayout = 'conditions';

    private $ruleFactory;

    private $CustomConditionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Rule\Block\Conditions $conditions,
        \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $rendererFieldset,
        \VendoreName\AddConditionFiled\Model\CustomConditionFactory $CustomConditionFactory,
        array $data = []
    ) {
        $this->_rendererFieldset = $rendererFieldset;
        $this->_conditions = $conditions;
        $this->CustomConditionFactory = $CustomConditionFactory;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    private function getRuleFactory()
    {
        if ($this->ruleFactory === null) {
            $this->ruleFactory = ObjectManager::getInstance()->get('VendoreName\AddConditionFiled\Model\CustomConditionFactory');
        }
        return $this->ruleFactory;
    }

    public function getTabClass()
    {
        return null;
    }

    public function getTabUrl()
    {
        return null;
    }

    public function isAjaxLoaded()
    {
        return false;
    }

    public function getTabLabel()
    {
        return __('Conditions');
    }

    public function getTabTitle()
    {
        return __('Conditions');
    }

    public function canShowTab()
    {
        return true;
    }

    public function isHidden()
    {
        return false;
    }

    protected function _prepareForm()
    {
        $model = $this->_coreRegistry->registry('current_rule');
        $form = $this->addTabToForm($model);
        $this->setForm($form);

        return parent::_prepareForm();
    }

    protected function addTabToForm(
        $model,
        $fieldsetId = 'conditions_serialized_field',
        $formName = 'custom_condition_form'
    ) {
        if (!$model) {
            $id = $this->getRequest()->getParam('rule_id');
            $model = $this->getRuleFactory()->create();
            $model->load($id);
        }
        $conditionsFieldSetId = $model->getConditionsFieldSetId($formName);
        $newChildUrl = $this->getUrl(
            'catalog_rule/promo_catalog/newConditionHtml/form/' . $conditionsFieldSetId,
            ['form_namespace' => $formName]
        );

        $form = $this->_formFactory->create();
        $form->setHtmlIdPrefix('rule_');
        $renderer = $this->_rendererFieldset->setTemplate(
            'Magento_CatalogRule::promo/fieldset.phtml'
        )->setNewChildUrl(
            $newChildUrl
        )->setFieldSetId(
            $conditionsFieldSetId
        );

        $fieldset = $form->addFieldset(
            $fieldsetId,
            [
                'legend' => __(
                    'Apply the rule only if the following conditions are met (leave blank for all products).'
                ),
            ]
        )->setRenderer(
            $renderer
        );
        $fieldset->addField(
            'conditions',
            'text',
            [
                'name' => 'conditions',
                'label' => __('Conditions'),
                'title' => __('Conditions'),
                'required' => true,
                'data-form-part' => $formName,
            ]
        )->setRule(
            $model
        )->setRenderer(
            $this->_conditions
        );
        $form->setValues($model->getData());
        $this->setConditionFormName($model->getConditions(), $formName);
        return $form;
    }

    private function setConditionFormName(\Magento\Rule\Model\Condition\AbstractCondition $conditions, $formName)
    {
        $conditions->setFormName($formName);
        if ($conditions->getConditions() && is_array($conditions->getConditions())) {
            foreach ($conditions->getConditions() as $condition) {
                $this->setConditionFormName($condition, $formName);
            }
        }
    }
}

Click Here For Part 3

0

Follow Below Steps:

Step-1: Create registration.php at app/code/VendoreName/AddConditionFiled

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'VendoreName_AddConditionFiled',
    __DIR__
);

Step-2: Create module.xml at app/code/VendoreName/AddConditionFiled/etc

<?xml version="1.0"?>
 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="VendoreName_AddConditionFiled" setup_version="1.0.1">
        <sequence>
           <module name="Magento_Checkout"></module>
           <module name="Magento_Catalog"></module>
       </sequence>
    </module>
</config>

Step-3: Create InstallSchema.php at app/code/VendoreName/AddConditionFiled/Setup

<?php

namespace VendoreName\AddConditionFiled\Setup;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        if (!$installer->tableExists('VendoreName_custom_condition')) {
            $tableName = $installer->getTable('VendoreName_custom_condition');
            $table = $installer->getConnection()
                ->newTable($tableName)
                ->addColumn(
                    'rule_id',
                    Table::TYPE_INTEGER,
                    10,
                    [
                        'identity' => true,
                        'nullable' => false,
                        'primary' => true,
                    ],
                    'Rule ID'
                )
                ->addColumn(
                    'rule_status',
                    Table::TYPE_INTEGER,
                    null,
                    [
                        'nullable' => true,
                        'default' => null,
                    ],
                    'Rule Status'
                )
                ->addColumn(
                    'rule_name',
                    Table::TYPE_TEXT,
                    255,
                    [
                        'nullable' => true,
                        'default' => null,
                    ],
                    'Rule Name'
                )
                ->addColumn(
                    'conditions_serialized',
                    Table::TYPE_TEXT,
                    '2M',
                    [],
                    'Conditions Serialized'
                )
                ->addColumn(
                    'actions_serialized',
                    Table::TYPE_TEXT,
                    '2M',
                    [],
                    'Actions Serialized'
                )
                ->addColumn(
                    'create_date',
                    \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                    null,
                    [
                        'nullable' => false,
                        'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT,
                    ],
                    'Create Date Time'
                )
                ->setComment('VendoreName Demo For Condition Field')
                ->setOption('type', 'InnoDB')
                ->setOption('charset', 'utf8');
            $installer->getConnection()->createTable($table);
        }
        $installer->endSetup();
    }
}

Here conditions_serialized and actions_serialized are used to store condition field value. So you must be add into you table. After creating table we add resource model and collection. Our Model name is CustomCondition.

Step-4: Create CustomCondition.php at app/code/VendoreName/AddConditionFiled/Model

<?php

namespace VendoreName\AddConditionFiled\Model;

use VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition as CustomConditionResourceModel;
use Magento\Quote\Model\Quote\Address;
use Magento\Rule\Model\AbstractModel;

class CustomCondition extends AbstractModel
{
    protected $_eventPrefix = 'VendoreName_addconditionfiled';
    protected $_eventObject = 'rule';
    protected $condCombineFactory;
    protected $condProdCombineF;
    protected $validatedAddresses = [];
    protected $_selectProductIds;
    protected $_displayProductIds;

    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Magento\CatalogRule\Model\Rule\Condition\CombineFactory $condCombineFactory,
        \Magento\SalesRule\Model\Rule\Condition\Product\CombineFactory $condProdCombineF,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        array $data = []
    ) {
        $this->condCombineFactory = $condCombineFactory;
        $this->condProdCombineF = $condProdCombineF;
        parent::__construct($context, $registry, $formFactory, $localeDate, $resource, $resourceCollection, $data);
    }

    protected function _construct()
    {
        parent::_construct();
        $this->_init(CustomConditionResourceModel::class);
        $this->setIdFieldName('rule_id');
    }

    public function getConditionsInstance()
    {
        return $this->condCombineFactory->create();
    }

    public function getActionsInstance()
    {
        return $this->condCombineFactory->create();
    }

    public function hasIsValidForAddress($address)
    {
        $addressId = $this->_getAddressId($address);
        return isset($this->validatedAddresses[$addressId]) ? true : false;
    }

    public function setIsValidForAddress($address, $validationResult)
    {
        $addressId = $this->_getAddressId($address);
        $this->validatedAddresses[$addressId] = $validationResult;
        return $this;
    }

    public function getIsValidForAddress($address)
    {
        $addressId = $this->_getAddressId($address);
        return isset($this->validatedAddresses[$addressId]) ? $this->validatedAddresses[$addressId] : false;
    }

    private function _getAddressId($address)
    {
        if ($address instanceof Address) {
            return $address->getId();
        }
        return $address;
    }

    public function getConditionsFieldSetId($formName = '')
    {
        return $formName . 'rule_conditions_fieldset_' . $this->getId();
    }

    public function getActionFieldSetId($formName = '')
    {
        return $formName . 'rule_actions_fieldset_' . $this->getId();
    }

    public function getMatchProductIds()
    {
        $productCollection = \Magento\Framework\App\ObjectManager::getInstance()->create(
            '\Magento\Catalog\Model\ResourceModel\Product\Collection'
        );
        $productFactory = \Magento\Framework\App\ObjectManager::getInstance()->create(
            '\Magento\Catalog\Model\ProductFactory'
        );
        $this->_selectProductIds = [];
        $this->setCollectedAttributes([]);
        $this->getConditions()->collectValidatedAttributes($productCollection);
        \Magento\Framework\App\ObjectManager::getInstance()->create(
            '\Magento\Framework\Model\ResourceModel\Iterator'
        )->walk(
            $productCollection->getSelect(),
            [[$this, 'callbackValidateProductCondition']],
            [
                'attributes' => $this->getCollectedAttributes(),
                'product' => $productFactory->create(),
            ]
        );
        return $this->_selectProductIds;
    }

    public function callbackValidateProductCondition($args)
    {
        $product = clone $args['product'];
        $product->setData($args['row']);
        $websites = $this->_getWebsitesMap();
        foreach ($websites as $websiteId => $defaultStoreId) {
            $product->setStoreId($defaultStoreId);
            if ($this->getConditions()->validate($product)) {
                $this->_selectProductIds[] = $product->getId();
            }
        }
    }

    protected function _getWebsitesMap()
    {
        $map = [];
        $websites = \Magento\Framework\App\ObjectManager::getInstance()->create(
            '\Magento\Store\Model\StoreManagerInterface'
        )->getWebsites();
        foreach ($websites as $website) {
            if ($website->getDefaultStore() === null) {
                continue;
            }
            $map[$website->getId()] = $website->getDefaultStore()->getId();
        }
        return $map;
    }
}

Step-5: Create CustomCondition.php at app/code/VendoreName/AddConditionFiled/Model/ResourceModel

<?php

namespace VendoreName\AddConditionFiled\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class CustomCondition extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('VendoreName_custom_condition', 'rule_id');
    }
}

Step-6: Create Collection.php at app/code/VendoreName/AddConditionFiled/Model/ResourceModel/CustomCondition

<?php

namespace VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition;

use VendoreName\AddConditionFiled\Model\CustomCondition as CustomConditionModel;
use VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition as CustomConditionResourceModel;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init(
            CustomConditionModel::class,
            CustomConditionResourceModel::class
        );
    }
}

Step-7: Create Collection.php at app/code/VendoreName/AddConditionFiled/Model/ResourceModel/CustomCondition/Grid

<?php

namespace VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition\Grid;

use VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition\Collection as CustomConditionCollection;
use Magento\Framework\View\Element\UiComponent\DataProvider\Document as CustomConditionModel;

class Collection extends CustomConditionCollection implements \Magento\Framework\Api\Search\SearchResultInterface
{
    protected $aggregations;

    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        $mainTable,
        $eventPrefix,
        $eventObject,
        $resourceModel,
        $model = CustomConditionModel::class,
        $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
        $this->_eventPrefix = $eventPrefix;
        $this->_eventObject = $eventObject;
        $this->_init($model, $resourceModel);
        $this->setMainTable($mainTable);
    }

    public function getAggregations()
    {
        return $this->aggregations;
    }

    public function setAggregations($aggregations)
    {
        $this->aggregations = $aggregations;
    }

    public function getAllIds($limit = null, $offset = null)
    {
        return $this->getConnection()->fetchCol($this->_getAllIdsSelect($limit, $offset), $this->_bindParams);
    }

    public function getSearchCriteria()
    {
        return null;
    }

    public function setSearchCriteria(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria = null)
    {
        return $this;
    }

    public function getTotalCount()
    {
        return $this->getSize();
    }

    public function setTotalCount($totalCount)
    {
        return $this;
    }

    public function setItems(array $items = null)
    {
        return $this;
    }
}

Step-8: Create di.xml at app/code/VendoreName/AddConditionFiled/etc

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">

    <virtualType name="VendoreNameAddConditionFiledFilterPool"
                 type="Magento\Framework\View\Element\UiComponent\DataProvider\FilterPool">
        <arguments>
            <argument name="appliers" xsi:type="array">
                <item name="regular" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter</item>
                <item name="fulltext" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\FulltextFilter</item>
            </argument>
        </arguments>
    </virtualType>

    <virtualType name="VendoreNameAddConditionFiledFilterPool"
                 type="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider">
        <arguments>
            <argument name="collection" xsi:type="object" shared="false">VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition\Collection</argument>
            <argument name="filterPool" xsi:type="object" shared="false">VendoreNameAddConditionFiledFilterPool</argument>
        </arguments>
    </virtualType>

    <type name="VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition\Grid\Collection">
        <arguments>
            <argument name="mainTable" xsi:type="string">VendoreName_custom_condition</argument>
            <argument name="eventPrefix" xsi:type="string">VendoreName_custom_condition_grid_collection</argument>
            <argument name="eventObject" xsi:type="string">VendoreName_custom_condition_grid_collection</argument>
            <argument name="resourceModel" xsi:type="string">VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition</argument>
        </arguments>
    </type>

    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="custom_condition_listing_data_source" xsi:type="string">VendoreName\AddConditionFiled\Model\ResourceModel\CustomCondition\Grid\Collection</item>
            </argument>
        </arguments>

    </type>
</config>

Step-9: Create routes.xml at app/code/VendoreName/AddConditionFiled/etc/adminhtml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="admin">
        <route id="addconditionfiled" frontName="addconditionfiled">
            <module name="VendoreName_AddConditionFiled" before="Magento_Backend"/>
        </route>
    </router>
</config>

Step-10: Create Index.php at app/code/VendoreName/AddConditionFiled/Controller/Adminhtml/Index

<?php

namespace VendoreName\AddConditionFiled\Controller\Adminhtml\Index;

class Index extends \Magento\Backend\App\Action
{
    protected $resultPageFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Add Rules'));
        return $resultPage;
    }
}

Step-11: Create menu.xml at app/code/VendoreName/AddConditionFiled/etc/adminhtml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/menu.xsd">
   <menu>
        <add id="VendoreName_AddConditionFiled::VendoreName_addconditionfiled"
             title="VendoreName - Add Condition Field"
             translate="title"
             module="VendoreName_AddConditionFiled"
             sortOrder="10"
             parent="Magento_Backend::marketing"
             resource="VendoreName_AddConditionFiled::VendoreName_addconditionfiled" />

        <add id="VendoreName_AddConditionFiled::menu"
             title="Add Rules"
             module="VendoreName_AddConditionFiled"
             sortOrder="100"
             parent="VendoreName_AddConditionFiled::VendoreName_addconditionfiled"
             action="addconditionfiled/index/index"
             resource="VendoreName_AddConditionFiled::menu"/>
    </menu>
</config>

Click Here For Part 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.