我在magento 2.3中创建了可扩展供应商目录列表产品功能的小部件。默认情况下,目录列表产品(CLP)不允许在同一页面上创建和处理多个条件控件。我的小部件允许创建几个条件控件。从技术上讲,我的每个条件控件都在新的模式窗口中打开。当用户需要创建条件时,他必须单击名为“ Choose”的按钮。Modal窗口打开,用户设置条件。当用户配置好并准备保存条件时,他单击发送到服务器的模态窗口ajax请求上名为“保存”的按钮,服务器将解码后的值响应给父表单输入。用户关闭模式窗口,然后单击父表单上的“保存”按钮。小部件已保存。全部做完。一切正确,直到此步骤:
但是前置数据变得不可交互-用户无法编辑和删除已加载的规则。widget.xml
First Conditions 1
</item>
</data>
</block>
</parameter>
MonteShot \ MegaWidget \ Block \ Adminhtml \ Conditions \ Conditions
response = $response; $this->conditionsHelper = $conditionsHelper; $this->ruleFactory = $ruleFactory; $this->ruleModelFactory = $ruleModelFactory; $this->_pageFactory = $pageFactory; $this->coreRegistry = $coreRegistry; $this->rendererFieldset = $rendererFieldset; $this->conditions = $conditions; parent::__construct($context, $coreRegistry, $formFactory, $data); } /** * {@inheritdoc} */ public function getTabLabel() { return __('Conditions'); } /** /** * @param \Magento\Framework\Data\Form\Element\AbstractElement $element * @return \Magento\Framework\Data\Form\Element\AbstractElement * @throws \Magento\Framework\Exception\LocalizedException */ public function prepareElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) { $uniqId = $this->mathRandom->getUniqueHash($element->getId()); $sourceUrl = $this->getUrl( 'megawidget/conditions_rule_conditioncontent/conditionpagecontroller', [ 'name' => $element->getData('name'), 'uniq_id' => $uniqId, 'button_num' => $this->getData('condition')[key($this->getData('condition'))] ]); $chooser = $this->getLayout()->createBlock( \MonteShot\MegaWidget\Block\Adminhtml\Widget\Chooser::class )->setElement( $element )->setConfig( $this->getConfig() )->setFieldsetId( $this->getFieldsetId() )->setSourceUrl( $sourceUrl )->setUniqId( $uniqId )->setValue($this->getData('condition')[key($this->getData('condition'))]); if ($element->getValue()) { $page = $this->_pageFactory->create()->load((int)$element->getValue()); if ($page->getId()) { $chooser->setLabel($this->escapeHtml($page->getTitle())); } } $element->setData('after_element_html', $chooser->toHtml()); return $element; } /** * Prepare form before rendering HTML * * @return Generic * @throws \Magento\Framework\Exception\LocalizedException */ 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), '[]'); /** @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'); // $model->setData('element_value', substr_replace($_POST['element_value'], '', 0, 26)); $model->getConditions()->setJsFormObject('rule_conditions_fieldset'); $fieldset->addField( 'conditions', 'text', ['name' => 'conditions', 'label' => __('Conditions'), 'title' => __('Conditions')] )->setRule( $model )->setRenderer( $this->conditions ); $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' => ' ']); $fieldset->addField( 'script-area', 'hidden', ['name' => 'select', 'class' => 'script-area-hidden', 'data_attribute' => [ 'mage-init' => ['hidden' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']], ], 'after_element_html' => ' ']); // $model->getConditions()->setJsFormObject('rule_conditions_fieldset'); $form->setValues($model->getData()); $this->setForm($form); return parent::_prepareForm(); } } //Magento\Widget\Helper\Conditions encode when save button has been pressed 和模态窗口中的代码 $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), '[]'); /** @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'); // $model->setData('element_value', substr_replace($_POST['element_value'], '', 0, 26)); $model->getConditions()->setJsFormObject('rule_conditions_fieldset'); $fieldset->addField( 'conditions', 'text', ['name' => 'conditions', 'label' => __('Conditions'), 'title' => __('Conditions')] )->setRule( $model )->setRenderer( $this->conditions ); // $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' => ' ']); $fieldset->addField( 'script-area', 'hidden', ['name' => 'select', 'class' => 'script-area-hidden', 'data_attribute' => [ 'mage-init' => ['hidden' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']], ], 'after_element_html' => ' ']); $form->setValues($model->getData()); $this->setForm($form); return parent::_prepareForm(); } PrepareData控制器 jsonHelper = $jsonHelper; $this->resultJsonFactory = $resultJsonFactory; $this->conditionsHelper = $conditionsHelper; parent::__construct($context, $coreRegistry, $fileFactory, $dateFilter, $ruleFactory, $logger); } /** * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface|void */ public function execute() { if (!$this->getRequest()->getPostValue()) { $this->_redirect('megawidget/*/'); } try { $serializedConditionArray = $this->conditionsHelper->decode($this->getRequest()->getParam('serializedArray')); $templateArray = []; foreach ($serializedConditionArray as $index => $singleArrItem) { if ($singleArrItem['name'] == 'form_key') { unset($serializedConditionArray[$index]); continue; } if ($singleArrItem['name'] == 'select') { unset($serializedConditionArray[$index]); continue; } if (!empty($templateArray[str_replace('rule', '', $singleArrItem['name'])])) { $templateArray[str_replace('rule', '', $singleArrItem['name'])] .= ',' . $singleArrItem['value']; } else { $templateArray[str_replace('rule', '', $singleArrItem['name'])] = $singleArrItem['value']; } //$templateArray[str_replace('rule', '', $singleArrItem['name'])] = $singleArrItem['value']; } $finalArr = []; foreach ($templateArray as $index => $data) { $indexName = $this->get_string_between(str_replace('[conditions]', '', $index), '[', ']'); $paramName = $this->get_string_between(str_replace('[conditions][' . $indexName . ']', '', $index), '[', ']'); $multiValue = str_replace('parameters[conditions][' . $indexName . ']' . '[' . $paramName . ']', '', $index); if ($paramName == 'value' && strpos($data, ',')) { $finalArr[$indexName][$paramName] = [$data]; } else { $finalArr[$indexName][$paramName] = $data; } if ($paramName == 'value' && $multiValue == '[]') { if ($finalArr[$indexName][$paramName]) { if ($finalArr[$indexName][$paramName]) { $temp = $finalArr[$indexName][$paramName]; unset($finalArr[$indexName][$paramName]); $finalArr[$indexName][$paramName][0] = $data; } else { $finalArr[$indexName][$paramName][0] .= ',' . $data; } } else { $finalArr[$indexName][$paramName][0] = [$data]; } } } $this->data = $this->conditionsHelper->encode($finalArr); $this->message = 'success'; } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); $id = (int)$this->getRequest()->getParam('rule_id'); if (!empty($id)) { $this->_redirect('megawidget/*/edit', ['id' => $id]); } else { $this->_redirect('megawidget/*/new'); } return; } catch (\Exception $e) { $this->messageManager->addErrorMessage( __('Something went wrong while saving the rule data. Please review the error log.') ); $this->error = $e->getMessage(); $this->message = 'success'; $this->logger->critical($e); $data = !empty($data) ? $data : []; $this->_session->setPageData($data); $this->_redirect('megawidget/*/edit', ['id' => $this->getRequest()->getParam('rule_id')]); return; } $resultJson = $this->resultJsonFactory->create(); $resultData = substr(substr($this->jsonHelper->jsonEncode($this->data), 1), 0, -1); return $resultJson->setData([ 'message' => $this->message, 'data' => $resultData, 'error' => $this->error ]); } protected function get_string_between($string, $start, $end) { $string = ' ' . $string; $ini = strpos($string, $start); if ($ini == 0) return ''; $ini += strlen($start); $len = strpos($string, $end, $ini) - $ini; return substr($string, $ini, $len); } } 控制器返回准备在jQuery中添加的数据 combineModelFactory = $combineModelFactory; $this->ruleCatalogFactory = $ruleCatalogFactory; $this->jsonHelper = $jsonHelper; $this->resultJsonFactory = $resultJsonFactory; $this->conditions = $conditions; parent::__construct($context, $coreRegistry, $fileFactory, $dateFilter, $ruleFactory, $logger); } public function execute() { if (!empty($this->getRequest()->getParam('id'))) { $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( 'conditions' ); if (!empty($typeArr[1])) { $model->setAttribute($typeArr[1]); } if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) { $model->setJsFormObject($this->getRequest()->getParam('form')); $html = $model->asHtmlRecursive(); } else { $html = ''; } return $this->getResponse()->setBody($html); } elseif (!empty($this->getRequest()->getParam('JsonToHtml'))) { $conditionDecoded = $this->conditions->decode($this->getRequest()->getParam('JsonToHtml')); foreach ($conditionDecoded as $idx => $condition) { if ($idx == '1') { continue; } else { $id = $idx; $type = $conditionDecoded[$idx]['type']; $rule = $this->ruleCatalogFactory->create(); // $rule->setConditions($conditionDecoded); $combineModel = $this->combineModelFactory->create(); $combineModel->loadArray($conditionDecoded); $validateResult = $rule->validateData(new \Magento\Framework\DataObject($rule->getData())); if ($validateResult !== true) { foreach ($validateResult as $errorMessage) { $this->message = $errorMessage; } return; } $rule->loadPost($rule->getData()); $model = $this->_objectManager->create( $type )->setId( $id )->setType( $type )->setPrefix( 'conditions' )->setData( 'conditions', $rule )->setRule( $rule ); if (!empty($conditionDecoded[$idx]['attribute'])) { $model->setAttribute($conditionDecoded[$idx]['attribute']); } if (!empty($conditionDecoded[$idx]['value'])) { $model->setValue($conditionDecoded[$idx]['value']); } } if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) { // if (empty($this->data)) { // $model->setJsFormObject($this->getRequest()->getParam('form')); // $this->data = '版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。