如何将产品的属性值复制到Magento中的另一个属性?



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;
    }
}

我能够在产品编辑页面中看到"哈哈哈"作为属性值。我想将其更改为另一个属性的值。我该怎么做?如何从此类访问同一产品的另一个属性值?

PS:我实际上想要实现的是这个。属性 X 的类型为多选类型,具有 100 多个选项。因此,属性 Y 必须跟踪从 X 中选择的选项,而 Y 以只读格式显示产品页面中的值。

我终于解决了这个问题。我采用了不同的方法,我使用了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;
}

我的配置.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,最后保存我的产品。

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

最新更新