浏览文章

文章信息

Magento2 无法保存属性|can't save product attribute values|can't update product value 14024

我花了很多时间在庞大的文件系统和各个插件观察者等之间定位这个问题。

1、代码定位

$product->getCustomAttribute('custom_data')

2、一旦你在插件Magento\Catalog\Model\Product的load方法中使用上面的代码,将造成产品数据会被更新,也就是你将无法保存新的数据,而是一直保存旧的数据。

下面是正确的代码和引发错误的代码(注释掉的部分)

 /**
     * @Desc         | 加载之后载入信息
     * @param Product $object
     * @param $product
     */
    function afterLoad(
        Product $object,
        $product
    )
    {
        // 数据准备
        $custom_data = [];
        //if($product->getCustomAttribute('custom_data'))
        //    $custom_data = json_decode($product->getCustomAttribute('custom_data')->getValue(), 1);
        if ($product->getData('custom_data'))
            $custom_data = json_decode($product->getData('custom_data'), 1)
        $product->setCustomAttribute('custom_data', json_encode($custom_data));
        return $product;
    }

以下的代码就是造成错误的原因,采用$product->getData('custom_data')可避免后天属性保存时不更新的问题。

//if($product->getCustomAttribute('custom_data'))
//$custom_data = json_decode($product->getCustomAttribute('custom_data')->getValue(), 1);

修改成

if ($product->getData('custom_data'))
            $custom_data = json_decode($product->getData('custom_data'), 1)

将正常工作!

原创