【问题标题】:How to copy a product's attributes value to another attribute in Magento?如何将产品的属性值复制到 Magento 中的另一个属性?
【发布时间】:2014-02-28 17:52:47
【问题描述】:

Magento 中有没有一种方法可以通过编程将属性 X 的值分配给属性 Y?

到目前为止,我已经尝试过了。我使用以下设置创建了 Y 属性:

$setup->addAttribute('catalog_product','myAttribute',array(
                   'group'=>'General',
                   'input'=>'label',
                   'type'=>'varchar',
                   'label'=>'Value of Attribute X',
                   'visible'=>1,
                   'backend'=>'beta/entity_attribute_backend_myattribute',
                   'global'=>Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE
               ));

在我的后端模型中,我这样做了:

class Namespace_Module_Model_Entity_Attribute_Backend_Myattribute extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
    public function beforeSave($object){
        $attrCode = $this->getAttribute()->getAttributeCode();
        $object->setData($attrCode,'HAHAHA');
        parent::beforeSave($object);
        return $this;
    }
}

我可以在产品编辑页面中看到“HAHAHA”作为属性值。我想将其更改为另一个属性的值。我该怎么做 ?如何从这个类中访问同一产品的另一个属性值?

PS:我真正想要实现的是这个。属性 X 是具有 100 个选项的多选类型。所以属性 Y 必须跟踪 X 选择的选项,并且 Y 在产品页面中以只读格式显示该值。

【问题讨论】:

    标签: magento


    【解决方案1】:

    我终于解决了这个问题。我采用了不同的方法,我使用了 Observer。 这就是我所做的:

    我用以下代码创建了一个观察者:

    class Namespace_Module_Model_Observer
    {
    
    private $_processFlag; //to prevent infinite loop of event-catch situation
    public function  copyAttribute($observer){
    
        if(!$this->_processFlag):
    
        $this->_processFlag=true;
        $_store = $observer->getStoreId();
        $_product = $observer->getProduct();
        $_productid = $_product->getId();
    
        $attrA = $_product->getAttributeText('attributeA'); //get attribute A's value
    
        $action = Mage::getModel('catalog/resource_product_action');
        $action->updateAttributes(array($_productid), array('attributeB'=>$attrA),$_store); //assign attrA's value to attrB
        $_product->save();
        endif;
    }
    

    我的 config.xml 是这样的:

    <events>
                <catalog_product_save_after>
                    <observers>
                        <namespace_module>
                            <type>singleton</type>
                            <class>Namespace_Module_Model_Observer</class>
                            <method>copyAttribute</method>
                        </namespace_module>
                    </observers>
                </catalog_product_save_after>
            </events>
    

    所以基本上,我使用的是事件 catalog_product_save_after,每当保存产品时就会触发该事件。在我的观察者中,我捕捉到事件,获取属性A的值并分配给属性B,最后保存我的产品。

    就是这样!我不知道这是否是最好的方法,但它确实有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多