Here’s how to programmatically, meaning through code, set a product’s attribute value when the attribute is of type Dropdown or Multiselect. For dropdown, we’ll be interested in setting only a single value. And obviously for multiselect, we’ll be interested in setting multiple values.
With Text attributes such as Name and Description, you can do something like:
$product->setName( 'My Sweet Shirt' ); $product->setDescription( 'This shirt will make you look good, thus impressing girls.' );
Unfortunately, this won’t work for attributes whose values are predefined. Instead of cursing Magento, think of it as a data-integrity/validation measure.
Anyway, assuming you already have a $product object, our overall process will be to:
- Load an attribute object for the attribute you want to work on
- Load the collection of that attribute’s values
- Make your choices (different for Dropdown and Multiselect)
- Save the product
1. Load an attribute object for the attribute you want to work on
$attribute = Mage::getModel('eav/entity_attribute');
$attribute->loadByCode( 4, 'color' );
2. Load the collection of that attribute’s values
$values = array();
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter( $attribute->getId() )
->setStoreFilter( Mage_Core_Model_App::ADMIN_STORE_ID, false)
->load();
foreach ($valuesCollection as $item) {
$values[$item->getValue()] = $item->getId();
}
3. Make your choice – DROPDOWN
$product->setColor( $values['Blue'] ); // just do whatever you need to code 'Blue' instead of hard-coding it
3. Make your choices – MULTISELECT
$product->addData( array( 'color' => $values['Blue'] .','. $values['Red'] .','. $values['Black'] // just putting together a comma-separated list of values ) );
4. Save the product
$product->save();
如何通过代码设置产品属性值

本文详细介绍了如何使用代码设置产品属性值,包括单选和多选类型的属性。通过加载属性对象、加载属性值集合并进行选择,最终保存产品。此教程适用于Magento平台。
3049

被折叠的 条评论
为什么被折叠?



