Мой контроль состояния в виджете в модальном окне не позволяет редактировать существующее условие, но позволяет создавать и сохранять новые - PullRequest
0 голосов
/ 09 октября 2019

Я создаю виджет в magento 2.3, который расширяет функциональность поставщика. По умолчанию Каталог товаров списка (CLP) не позволяет создавать и обрабатывать несколько элементов управления условиями на одной странице. Мой виджет позволяет создать несколько условий контроля. Технически каждый мой контроль состояния открывается в новом модальном окне. Когда пользователю необходимо создать условие, он должен нажать на кнопку «Выбрать», откроется модальное окно, и пользователь установит условия. Когда пользователь настраивает и готов сохранить условие, он нажимает кнопку «Сохранить» в модальном окне ajax-запроса, отправляющего серверу, и сервер отвечает декодированным значением на вход родительской формы. Пользователь закрывает модальное окно и нажимает кнопку Сохранить в родительской форме. Виджет сохранен. Все сделано. До этого шага все в порядке: когда пользователь хочет отредактировать сохраненный виджет и открывает модальное окно, сохраненные данные преобразуются в применимую форму другим ajax и jQuery. Предварительно добавьте newchild

в

1 Ответ

0 голосов
/ 09 октября 2019
  protected function _prepareForm()
    {

        $model = $this->ruleFactory->create();
        // $model = $this->ruleModelFactory->create();

        $id = $this->_request->getParam('uniq_id');
        $name = $this->_request->getParam('name');
        $cuttedName = trim(str_replace('parameters', '', $name), '[]');
//        if ($this->ruleResourceCollection->getSize() == 0) {
//
//        } else {
//            if (!$id) {
//                $model = $this->ruleResourceCollection
//                    ->addFieldToFilter(\MonteShot\MegaWidget\Model\Rule::UNIQ_BUTTON_ID,
//                        $id
//                    )->load();
//            }
//        }

        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create(
            [
                'data' => [
                    'id' => 'edit_form_modal',
                    'action' => $this->getUrl('megawidget/conditions_rule/savewidget',
                        [
                            'uniq_id' => $this->_request->getParam('uniq_id'),
                            'button_num' => $this->_request->getParam('button_num'),
                            'name' => $this->_request->getParam('name'),
                        ]),
                    'method' => 'post',
                ],
            ]
        );
        $form->setUseContainer(true);
        $form->setHtmlIdPrefix('rule_');
        $this->getLayout()->createBlock("Magento\Widget\Block\Adminhtml\Widget\Options");
        $renderer = $this->rendererFieldset->setTemplate(
            'Magento_CatalogRule::promo/fieldset.phtml'
        )->setNewChildUrl(
            $this->getUrl('megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset')
        );

        $fieldset = $form->addFieldset(
            'conditions_fieldset',
            [
                'legend' => __(
                    'Apply the rule only if the following conditions are met (leave blank for all products).'
                )
            ]
        )->setRenderer(
            $renderer
        );


        $model->getConditions()->setJsFormObject('rule_conditions_fieldset');


        try {
            $conditions = $this->conditionsHelper->decode($this->getRequest()->getParam('element_value'));
            $model->loadPost(['conditions' => $conditions]);
        } catch (\InvalidArgumentException $invalidArgumentException) {
            //do nothing
        }

        $element = $fieldset->addField(
            'condition',
            'text',
            ['name' => 'conditions',
                'label' => __('Condition'),
                'title' => __('Condition'),
                'data_attribute' => [
                    'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']],
                ]
            ])
            ->setRule(
                $model
            )->setRenderer(
                $this->conditions
            );
        $sourceUrl = $this->getUrl(
            'megawidget/conditions_rule_conditioncontent/conditionmodalpagecontroller');
        $condition = $this->getLayout()->createBlock(
            \MonteShot\MegaWidget\Block\Adminhtml\Widget\Options::class
        )->setElement(
            $element
        )->setConfig(
            $this->getConfig()
        )->setFieldsetId(
            $this->getFieldsetId()
        )->setSourceUrl(
            $sourceUrl
        )->setConfig(
            $this->getConfig()
        )->setFieldsetId(
            $this->getFieldsetId()
        )->setUniqId(
            $id
        );


        // $fieldset->addElement($this->getLayout()->createBlock(\MonteShot\MegaWidget\Renderer\Conditions::class));
        $label = $id . 'label';
        $valueId = $id . 'value';
        $fieldset->addField(
            'button-save',
            'hidden',
            ['name' => 'select',
                'label' => __('Save condition'),
                'title' => __('Save condition'),
                'class' => 'action-close',
                'data-role' => 'closeBtn',
                'data_attribute' => [
                    'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form']],
                ],

                'after_element_html' => '

<button data-role="closeBtn" id="rule_button-save-submit-' . $cuttedName . '" type="button">Save</button>
<script>
require([\'jquery\',\'jqueryForm\',\'Magento_Ui/js/modal/modal\'], function (jQuery,jqueryForm,modal){

jQuery(document).on(\'click\', "#rule_button-save-submit-' . $cuttedName . '", function () {  

                var serArr=JSON.stringify(jQuery("#edit_form_modal").serializeArray());
                 jQuery.ajax({
               url: "' . $this->getUrl("megawidget/conditions_rule/preparedata") . '", 
               data: { form_key: window.FORM_KEY,serializedArray:serArr},
               type: \'post\',
                success: function (response) {
                              console.log(response.data);
                              jQuery("input[name=\'' . $name . '\']")[0].value=response.data;


                    },
                error: function (response) {
                                              alert(response.message);
                                               console.log(response.message);
                    }

                 }); 

});
});
</script>

']);
        $form->setValues($model->getData());
        $this->setForm($form);

        return parent::_prepareForm();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...