问题
Is there a way in Magento where I can assign Attribute X's value to Attribute Y programmatically ?
So far I have tried this. I created the Y attribute with following settings:
$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
));
In my backend model, I have done this:
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;
}
}
I am able to see "HAHAHA" as the attribute value in the Product Edit page. I want to change this to value of another attribute. How do I do it ? How do I access another attribute's value of the same product from this class ?
PS: What I am actually trying to achieve is this. The attribute X is of type multiselect with 100s of options. So the attribute Y must keep track of the options selected of X, and Y shows the value in product page in readonly format.
回答1:
I have solved this finally. I went by a different approach, I used Observer. This is what I did:
I created an Observer with following code:
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;
}
And my config.xml went like this:
<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>
So basically, I am using the event catalog_product_save_after which is fired whenever a product is saved. In my observer, I catch the event, get attributeA's value and assign to attributeB, and finally save my product.
That's it! I don't know if this is the best method, but it does work!
来源:https://stackoverflow.com/questions/22102367/how-to-copy-a-products-attributes-value-to-another-attribute-in-magento