Assigning An Attribute Option To A Product In Magento

 

Almost every company I’ve worked with has a catalog that requires the use of attribute options in Magento. This is great for layered navigation, product options, etc… The challenge comes in data imports because looking up option ids and assigning them to a new or existing product can be tricky.

Below I’ve detailed some code that can be helpful in looking up and assigning an option id to an attribute on a product:

/*
* Lets assume you have an attribute named 'fabric' with the options 'yarn' & 'cloth'
*/


$product = Mage::getModel('catalog/product');

$attributeId = $attModel->getIdByCode('catalog_product', 'fabric'); //the first parameter is entity_type and the second is attribute_code

$attribute = Mage::getModel('eav/entity_attribute')->load($attributeId);

$optionsArray = getAttributeOptions( $attribute );

$targetOptionId;
foreach( $optionsArray as $optionId => $optionString ){
    if( $optionString == 'cloth'){
        $targetOptionId = $optionId;
    }
}


$product->setData( array("fabric" => $targetOptionId) );

$product->save(); //Clearly in a real world scenario additional product data would be set before saving

/**
 * @returns  array() Where $index = optionId and $value = store option string
 * @important Remember that the string values returned will be based on the storeId assigned
 *            to the attribute via $attribute->setStoreId(#)
 */
public function getAttributeOptions(Mage_Eav_Model_Entity_Attribute $attribute, $storeId = null){
    $attOptionsModel = Mage::getModel('eav/entity_attribute_source_table');
    if($storeId == null){
        $attribute->setStoreId( Mage::app()->getStore()->getId() );
    } else {
        $attribute->setStoreId( $storeId );
    }
    $attOptionsModel->setAttribute($attribute);
    $optionsArray = $attOptionsModel->getAllOptions(false); //We pass false so it does not return empty options values
    return $optionsArray;

This concept can also help with programatically setting new options, which is a little trickier… When you decide its time to use this method to create a new option step very carefully through your programatic calls and the corresponding updates happening in the database.