Shopware 6插件:布尔配置转多选配置的迁移与旧配置删除
Shopware 6 评论自动发布配置迁移实现方案
一、替换插件配置XML
将原布尔型配置项替换为多选下拉配置,支持选择具体星级或None:
<input-field type="multiselect"> <name>reviewAutoPublishStars</name> <label>自动发布对应星级的评论</label> <defaultValue>["0"]</defaultValue> <!-- 与原默认值true行为一致 --> <options> <option> <value>none</value> <label>None(不自动发布任何评论)</label> </option> <option> <value>0</value> <label>0 Stars(自动发布所有星级评论)</label> </option> <option> <value>1</value> <label>1 Star</label> </option> <option> <value>2</value> <label>2 Stars</label> </option> <option> <value>3</value> <label>3 Stars</label> </option> <option> <value>4</value> <label>4 Stars</label> </option> <option> <value>5</value> <label>5 Stars</label> </option> </options> </input-field>
二、实现配置迁移的Update方法
- 先在插件类中注入
SystemConfigService,用于读写配置:
use Shopware\Core\System\SystemConfig\SystemConfigService; class YourPlugin extends Plugin { private SystemConfigService $systemConfigService; public function __construct(SystemConfigService $systemConfigService) { $this->systemConfigService = $systemConfigService; parent::__construct(); } }
- 修改
update方法,完成旧配置迁移、删除旧配置:
public function update(UpdateContext $context): void { parent::update($context); // 处理所有销售渠道的配置 $oldChannelConfigs = $this->systemConfigService->get('YourPlugin.config.reviewSkipModeration', null, true); foreach ($oldChannelConfigs as $salesChannelId => $oldValue) { $newValue = $oldValue === true ? ['0'] : ['none']; // 写入新配置 $this->systemConfigService->set( 'YourPlugin.config.reviewAutoPublishStars', $newValue, $salesChannelId ); // 删除旧配置项 $this->systemConfigService->delete( 'YourPlugin.config.reviewSkipModeration', $salesChannelId ); } // 处理全局配置(无销售渠道场景) $globalOldValue = $this->systemConfigService->get('YourPlugin.config.reviewSkipModeration'); if ($globalOldValue !== null) { $globalNewValue = $globalOldValue === true ? ['0'] : ['none']; $this->systemConfigService->set('YourPlugin.config.reviewAutoPublishStars', $globalNewValue); $this->systemConfigService->delete('YourPlugin.config.reviewSkipModeration'); } }
三、更新评论提交的业务逻辑
将原布尔判断逻辑替换为星级匹配逻辑,支持多选自动发布场景:
// 获取配置的自动发布星级列表 $autoPublishStars = $this->systemConfigService->get('YourPlugin.config.reviewAutoPublishStars', ['0']); // 若选中None,不自动发布 if (in_array('none', $autoPublishStars)) { $review->setIsActive(false); } else { // 获取当前评论的星级(需根据实际代码调整获取方式) $reviewRating = (string)$review->getRating(); // 匹配则自动发布 if (in_array($reviewRating, $autoPublishStars)) { $review->setIsActive(true); } else { $review->setIsActive(false); } }
四、兼容性说明
- 旧配置映射完全遵循要求:原
true映射为0 Stars(自动发布所有评论),原false映射为None(不自动发布) - 支持阈值场景:用户只需在配置中选中目标星级及以上(如3、4、5星),即可实现对应阈值的自动发布
- 所有现有用户的配置会被自动迁移,业务逻辑无感知切换,不影响现有功能
内容的提问来源于stack exchange,提问作者mlodhi
相关产品推荐
相关产品推荐

