1

I create custom module for add rule condition in custom module but not get condition data on edit time here i share my files

vendor_module_form.xml

<fieldset name="conditions_fieldset">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="label" xsi:type="string" translate="true">Conditions</item>
                        <item name="collapsible" xsi:type="boolean">false</item>
                    </item>
                </argument>
                <container name="conditions_serialized_container" >
                    <argument name="data" xsi:type="array">
                        <item name="config" xsi:type="array">
                            <item name="sortOrder" xsi:type="number">10</item>
                        </item>
                    </argument>
                    <htmlContent name="html_content">
                        <argument name="block" xsi:type="object">Vendor\Module\Block\Adminhtml\Message\Edit\Tab\Conditions</argument>
                    </htmlContent>
                </container>
            </fieldset>

Vendor\Module\Block\Adminhtml\Message\Edit\Tab\Conditions.php

<?php

namespace Vendor\Module\Block\Adminhtml\Message\Edit\Tab;

use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Backend\Block\Widget\Form\Generic;

class Conditions extends Generic implements TabInterface
{
    protected $rendererFieldset;

    protected $conditions;

    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,
        \Vendor\Module\Model\RuleFactory $labelFactory,
        array $data = []
    ) {
        $this->rendererFieldset = $rendererFieldset;
        $this->conditions = $conditions;
        $this->labelFactory = $labelFactory;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    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_label");
        $form = $this->addTabToForm($model);
        $this->setForm($form);
        return parent::_prepareForm();
    }

    protected function addTabToForm(
        $model,
        $fieldsetId = "conditions_fieldset",
        $formName = "message_form"
    ) {
        if (!$model) {
            $id = $this->getRequest()->getParam("id");
            $model = $this->labelFactory->create();
            $model->load($id);
        }

        $newChildUrl = $this->getUrl(
            "msg/message/newConditionHtml/form/conditions_fieldset"
        );

        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create();
        $form->setHtmlIdPrefix("rule_");
        $renderer = $this->rendererFieldset
            ->setTemplate("Magento_CatalogRule::promo/fieldset.phtml")
            ->setNewChildUrl($newChildUrl);

        $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);
            }
        }
    }
}

Vendor\Module\Controller\Adminhtml\Message\NewConditionHtml.php

<?php

namespace Vendor\Module\Controller\Adminhtml\Message;

class NewConditionHtml extends \Vendor\Module\Controller\Adminhtml\Message\Rule
{
    /**
     * New condition html action
     *
     * @return void
     */

    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        $labelFactory = $this->_objectManager->create('Vendor\Module\Model\RuleFactory');
        $typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type')));
        $type = $typeArr[0];
        $model = $this->_objectManager->create(
            $type
        )->setId(
            $id
        )->setType(
            $type
        )->setRule(
            $labelFactory->create()
        )->setPrefix(
            'conditions'
        );

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

        if ($model instanceof \Vendor\Module\Model\Condition\AbstractCondition) {
            $model->setFormName('message_form')->setJsFormObject('conditions_fieldset');
            $html = $model->asHtmlRecursive();
        } else {
            $html = '';
        }
        $this->getResponse()->setBody($html);
    }
}

Vendor\Module\Controller\Adminhtml\Message\Save.php

<?php

namespace Vendor\Module\Controller\Adminhtml\Message;

use Magento\Backend\App\Action;
use Magento\Backend\Model\Session;
use Vendor\Module\Model\MessageFactory;

class Save extends \Magento\Backend\App\Action
{
    /*
     * @var Message
     */
    protected $messageModel;
    /**
     * @var Session
     */
    protected $adminsession;
    /**
     * @param Action\Context $context
     * @param Message           $messageModel
     * @param Session        $adminsession
     */
    public function __construct(
        Action\Context $context,
        MessageFactory $messageModel,
        Session $adminsession
    ) {
        parent::__construct($context);
        $this->messageModel = $messageModel;
        $this->adminsession = $adminsession;
    }
    /**
     * Save message record action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {

        

        
        $resultRedirect = $this->resultRedirectFactory->create();

        $model = $this->messageModel->create();
        $data = $this->getRequest()->getPostValue();
        
        $customerGroup = implode(',',$data['customer_group']);
        $data['customer_group'] = $customerGroup;

        $website = implode(',',$data['website']);
        $data['website'] = $website;
        // echo "<pre>";
        // print_r($data);






        if ($data) {
            $id = $this->getRequest()->getParam('id');
            if ($id) {
                $data['updated_at'] = date("Y-m-d H:i:s");
                
                $model->load($id);
            }


            if (isset($data['rule']['conditions'])) {
                $data['conditions'] = json_encode($data['rule']['conditions']);
            }
            
            unset($data['rule']);
            // print_r($data['conditions']);
            // exit;
                
            $model->setData($data);
            try {
                $model->save();
                $this->messageManager->addSuccess(__('The data has been saved.'));
                $this->adminsession->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    if ($this->getRequest()->getParam('back') == 'add') {
                        return $resultRedirect->setPath('*/*/add');
                    } else {
                        return $resultRedirect->setPath('*/*/edit', ['id' => $model->getId(), '_current' => true]);
                    }
                }
                return $resultRedirect->setPath('*/*/');
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\RuntimeException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the data.'));
            }
            $this->_getSession()->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['id' => $this->getRequest()->getParam('id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
    
}

Vendor\Module\Model\DataProvider.php

<?php
namespace Vendor\Module\Model;
 
use Vendor\Module\Model\ResourceModel\Message\CollectionFactory;
 
class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
    private $loadedData;
    /**
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param CollectionFactory $messageCollectionFactory
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $messageCollectionFactory,
        array $meta = [],
        array $data = []
    ) {
        $this->collection = $messageCollectionFactory->create();
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    }
 
    /**
     * Get data
     *
     * @return array
     */
    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $items = $this->collection->getItems();
        foreach ($items as $blog) {
            
            $this->loadedData[$blog->getId()] = $blog->getData();
            $this->loadedData['conditions_fieldset'] = $blog->getData('conditions_fieldset');

        }
        return $this->loadedData;
    }
}

1 Answer 1

1

In that I just change my db_schema.xml file

the all code is correct just need to change the condition field name from "conditions" to "conditions_serialized"

than it's works fine

<column xsi:type="text" name="conditions_serialized" nullable="true" comment="Rule"/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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