Magento 2 如何通过PHP在cms_page_form中添加逐店动态输入字段
Magento 2 后台CMS页面表单动态生成多商店对应输入字段实现方案
- 第一步:注册表单元数据拦截插件
在自定义模块的etc/adminhtml/di.xml中添加如下配置,用来拦截CMS页面表单的UI元数据生成过程:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Cms\Ui\DataProvider\Page\Form\PageDataProvider"> <plugin name="add_store_wise_custom_field_to_cms_page" type="Vendor\Module\Plugin\Adminhtml\Cms\AddStoreWiseCustomField"/> </type> </config>
- 第二步:编写插件类动态生成对应每个商店的字段
创建插件文件Vendor/Module/Plugin/Adminhtml/Cms/AddStoreWiseCustomField.php,核心逻辑是获取所有商店列表,循环生成对应输入字段:
<?php namespace Vendor\Module\Plugin\Adminhtml\Cms; use Magento\Store\Model\StoreManagerInterface; use Magento\Cms\Ui\DataProvider\Page\Form\PageDataProvider; class AddStoreWiseCustomField { public function __construct( private StoreManagerInterface $storeManager ) {} /** * 动态插入多商店对应输入字段到表单 */ public function afterGetMeta(PageDataProvider $subject, array $meta): array { // 插入到general字段集下,可按需调整到其他字段集 if (!isset($meta['general']['children'])) { return $meta; } $storeList = $this->storeManager->getStores(); $sortOrder = 60; // 可调整排序位置 foreach ($storeList as $store) { $fieldKey = 'custom_store_field_' . $store->getId(); $meta['general']['children'][$fieldKey] = [ 'arguments' => [ 'data' => [ 'config' => [ 'label' => __('自定义字段 - %1', $store->getName()), 'dataType' => 'text', 'formElement' => 'input', 'visible' => true, 'required' => false, 'sortOrder' => $sortOrder++, 'dataScope' => $fieldKey, // 如需和商店切换器联动,加上下面这行配置即可 'scopeLabel' => __($store->getName()) ] ] ] ]; } return $meta; } /** * 回填已保存的字段值到表单 */ public function afterGetData(PageDataProvider $subject, array $data): array { $currentPage = $subject->getCurrentPage(); if (!$currentPage->getId()) { return $data; } // 此处替换为你自己的逻辑,从自定义存储表中读取对应CMS页面的各商店字段值 foreach ($this->storeManager->getStores() as $store) { $fieldKey = 'custom_store_field_' . $store->getId(); // 示例:假设从自定义表获取到值为$savedValue // $data[$currentPage->getId()][$fieldKey] = $savedValue; } return $data; } }
- 第三步:实现字段值保存逻辑
在自定义模块的etc/adminhtml/events.xml中注册CMS页面保存后事件,处理自定义字段的存储:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="cms_page_save_after"> <observer name="save_cms_page_custom_store_fields" instance="Vendor\Module\Observer\Adminhtml\Cms\SaveStoreWiseCustomField"/> </event> </config>
编写对应的观察者类,将提交的自定义字段值存入你提前创建的自定义表即可,自定义表需要包含page_id、store_id、custom_field_value三个核心字段。
提示:如果需要适配单商店模式,可在插件中先判断商店数量,只有多商店场景下才生成对应字段,避免冗余。
内容的提问来源于stack exchange,提问作者Pedro Amaro
相关产品推荐
相关产品推荐

