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

Magento商品复制时触发事件清空自定义EAN字段方案咨询

解决方案:复制商品时清空EAN字段

嘿,你找的product_duplicate_attributes事件完全适配你的需求!这个事件就是Magento专门在商品复制流程中触发的,用来控制属性复制的逻辑,刚好能帮你实现“复制商品时清空EAN字段”的需求。下面是具体的实现步骤:

1. 创建自定义模块(如果没有现成的)

首先你需要一个自定义模块来承载这个功能,模块的基础文件如下:

registration.php

<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_ClearEanOnDuplicate', __DIR__);

etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_ClearEanOnDuplicate" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

2. 配置事件观察者

在模块的etc/events.xml文件中,注册监听product_duplicate_attributes事件的观察者:

<?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="product_duplicate_attributes">
        <observer name="clear_ean_on_product_duplicate" instance="Vendor\ClearEanOnDuplicate\Observer\ClearEanOnDuplicate"/>
    </event>
</config>

3. 编写观察者逻辑

创建观察者类,在复制商品时清空EAN字段的值:

Observer/ClearEanOnDuplicate.php

<?php
namespace Vendor\ClearEanOnDuplicate\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ClearEanOnDuplicate implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        // 获取新生成的商品对象
        $newProduct = $observer->getEvent()->getNewProduct();
        
        // 替换为你实际的EAN属性代码(比如ean、custom_ean等)
        $eanAttributeCode = 'ean';
        
        // 清空EAN字段的值
        $newProduct->setData($eanAttributeCode, '');

        return $this;
    }
}

额外说明

  • 如果你不确定EAN属性的代码,可以在后台Stores > Attributes > Product中找到对应的EAN属性,查看它的“Attribute Code”值;
  • 这个方案比监听catalog_product_save_before更精准,因为后者会在所有商品保存操作(包括正常编辑保存)时触发,而我们只需要在商品复制时执行清空逻辑;
  • 部署完模块后,记得执行bin/magento setup:upgrade和缓存清理命令,让配置生效。

这样设置后,用户点击商品的「复制」按钮,新生成的商品EAN字段就会自动为空啦,完美匹配你的需求!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:45:40