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();