You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware后台自定义字段自动填充fallback语言,如何保留英文字段为空?

Shopware自定义字段清除英文内容后自动填充默认语言值的解决方法

问题场景

配置shoes_description自定义字段时,所有产品在默认语言de-DE下均有内容,但部分产品无需配置en-GB语言下的内容。操作流程如下:

  • 修改前状态:
    • de-DE:"Schwarze Schuhe"
    • en-GB:"Schwarze Schuhe"
  • 修改后预期状态:
    • de-DE:"Schwarze Schuhe"
    • en-GB:""
  • 实际保存刷新后状态:
    • de-DE:"Schwarze Schuhe"
    • en-GB:"Schwarze Schuhe"

en-GB语言下的字段会自动拉取默认语言的回退值,无法保持为空,需解决该问题。

解决方案

1. 后台配置调整(优先推荐)

Shopware后台提供了自定义字段的回退行为设置,可直接修改:

  • 进入后台设置 > 自定义字段
  • 找到目标字段shoes_description并点击编辑
  • 切换到「高级设置」标签页
  • 找到「回退行为」选项,将默认的「使用回退值」改为「不使用回退值」(或对应版本的「保留空值」选项)
  • 保存字段配置后,重新测试清除en-GB字段内容并保存,此时字段会保持为空状态

2. 代码层面自定义处理(适用于后台配置无效的场景)

如果后台配置无法满足需求,可通过事件订阅强制保留空值(以Shopware 6.x为例):

步骤1:创建事件订阅者

<?php

namespace YourPluginNamespace\Subscriber;

use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ProductCustomFieldSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ProductEvents::PRODUCT_WRITTEN_EVENT => 'onProductWritten',
        ];
    }

    public function onProductWritten(EntityWrittenEvent $event): void
    {
        foreach ($event->getWriteResults() as $result) {
            $payload = $result->getPayload();
            
            // 检查是否存在en-GB翻译及目标自定义字段
            if (!isset($payload['translations']['en-GB']['customFields']['shoes_description'])) {
                continue;
            }
            
            // 如果字段为空字符串,强制设置为null以阻止回退填充
            if ($payload['translations']['en-GB']['customFields']['shoes_description'] === '') {
                $payload['translations']['en-GB']['customFields']['shoes_description'] = null;
                $result->setPayload($payload);
            }
        }
    }
}

步骤2:注册订阅者

在插件的src/Resources/config/services.xml中添加以下配置:

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="YourPluginNamespace\Subscriber\ProductCustomFieldSubscriber">
            <tag name="kernel.event_subscriber"/>
        </service>
    </services>
</container>

步骤3:测试效果

安装并激活插件后,再次清除en-GB语言下的shoes_description字段内容并保存,字段将保持为空,不再自动填充默认语言的内容。


内容的提问来源于stack exchange,提问作者Matheus Gontijo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:42:41