以编程方式更改商店视图级别的产品属性

时间:2011-07-07 17:34:37

标签: magento

如果这个问题很简单,我很抱歉,但我一直在努力找到我在这里做错了什么。我试图在商店视图级别更改属性的值,但默认值也会更改,但不应该更改。当然,此属性设置为“store-view-scoped”。为了简单起见,我尝试了产品名称。没有成功。

以下是我尝试过的不成功的测试...

你看到我在这里做错了吗?

非常感谢。


我的尝试:

$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName('new_name')->save();

$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setStore(STORE_CODE)->setName('new_name')->save();

$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_CODE)->setName('new_name')->save();

$product = Mage::getModel('catalog/product')->setStoreId(STORE_ID)->load(PRODUCT_ID);
$product->setName('new_name')->save();

$product = Mage::getModel('catalog/product')->setStoreId(STORE_ID)->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName('new_name')->save();

我甚至尝试在产品型号加载之前添加以下行...

Mage::app()->setCurrentStore(STORE_ID);

3 个答案:

答案 0 :(得分:46)

因此,这是在特定商店视图中更改特定产品属性的属性值的完整代码段。产品名称示例:

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName('my_new_product_name')->save();

作为一个额外的答案,人们可​​能有兴趣将属性值更改为默认值。在这种情况下,必须将参数'false'传递给setAttribute:

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName(false)->save();

答案 1 :(得分:12)

您需要将当前商店设置为代码块顶部的admin:

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

答案 2 :(得分:3)

注意在使用某些商店视图的数据加载产品时,也会加载默认值。保存此类产品会将默认值保存为商店值(因此未设置"使用默认值"对于字段) 我最终得到了以下功能来清除默认值的产品数据

public static function _removeDefaults($item) {
    static $attributeCodes = null;
    if($attributeCodes == null) {
        $attributes = Mage::getSingleton('eav/config')
            ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection();
        $attributeCodes = array();
        foreach($attributes as $attribute) {
            $ac = $attribute->getAttributeCode();
            if(in_array($ac, array('sku','has_options','required_options','created_at','updated_at','category_ids'))) {
                continue;
            }
            $attributeCodes[] = $ac;
        }
    }
    foreach($attributeCodes as $ac) {
        if(false == $item->getExistsStoreValueFlag($ac)) {
            $item->unsetData($ac);
        }
    }
}

请记住只发送为某些商店视图加载的产品

相关问题