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

如何通过插件扩展设置分类自定义字段上传图片的默认存储位置?

Shopware自定义字段上传图片指定媒体文件夹解决方案

直接绑定文件夹ID到自定义字段

在创建自定义字段的代码里,给媒体类型的字段加上media_folder_id配置,直接关联你已有的文件夹ID。

示例代码(放在插件的Migration类或者自定义字段注册逻辑里):

// 先获取你创建的目标文件夹ID $targetFolderId
$customFieldRepo = $this->container->get('custom_field_set.repository');
$customFieldRepo->create([
    [
        'name' => 'category_custom_image_set',
        'config' => [
            'label' => ['zh-CN' => '分类自定义图片']
        ],
        'customFields' => [
            [
                'name' => 'category_custom_image',
                'type' => 'media',
                'config' => [
                    'label' => ['zh-CN' => '自定义图片'],
                    'media_folder_id' => $targetFolderId, // 这里填你的文件夹ID
                    'componentName' => 'sw-media-field'
                ]
            ]
        ],
        'relations' => [
            ['entityName' => 'category'] // 关联分类实体
        ]
    ]
], $context);

事件拦截强制指定存储路径

如果自定义字段已经建好,或者需要动态判断上传场景,用media.upload事件拦截上传行为,修改媒体文件的存储文件夹。

  1. 写事件订阅类:
<?php

namespace YourPlugin\Subscriber;

use Shopware\Core\Content\Media\Event\MediaUploadEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MediaUploadSubscriber implements EventSubscriberInterface
{
    private $targetFolderId;

    public function __construct(string $targetFolderId)
    {
        $this->targetFolderId = $targetFolderId;
    }

    public static function getSubscribedEvents(): array
    {
        return [MediaUploadEvent::class => 'onMediaUpload'];
    }

    public function onMediaUpload(MediaUploadEvent $event): void
    {
        $request = $event->getRequest();
        // 通过请求参数判断是否是你的自定义字段上传
        if ($request->get('field') === 'category_custom_image') {
            $event->getMedia()->setMediaFolderId($this->targetFolderId);
        }
    }
}
  1. 在插件的services.xml里注册这个订阅:
<service id="YourPlugin\Subscriber\MediaUploadSubscriber">
    <argument type="string">你的目标文件夹ID</argument>
    <tag name="kernel.event_subscriber"/>
</service>

验证操作

  • 执行bin/console cache:clear清理缓存
  • 进入后台分类页面,上传自定义字段的图片,检查媒体库是否存入指定文件夹

内容的提问来源于stack exchange,提问作者vm-developer-ph

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:42:59