The following code lets you update dropdown product attribute value.

Let’s say we have our dropdown product attribute already created test_attribute and it has “Yes”, “No” and empty (null) values. And we would like to update this attribute with the value “Yes”.  We need to get the the attrubite’s option value first. Here, option[‘value’] is saved as option id in eav_attribute_option table.

 

<?php 

public function attributeOptionIdExists($attributeCode, $attrbuteValue) 
{ 
    $attributeModel = Mage::getModel('eav/entity_attribute'); 
    $attributeSourceTable = Mage::getModel('eav/entity_attribute_source_table'); 

    $attributeId = $attributeModel->getIdByCode('catalog_product', $attribu teCode); 
    $attribute = $attributeModel->load($attributeId); 

    $attributeTable = $attributeSourceTable->setAttribute($attribute); 
    $options = $attributeSourceTable->getAllOptions(false); 

    foreach($options as $option) { 
      if ($option['label'] == $attrbuteValue) { 
          return $option['value']; 
      } 
    } 
    return false; 
} 

    $optionId = $this->attributeOptionIdExists('test_attribute', "Yes");
?>

 

Once, we get our attribute’s option id, we will be able to update that attribute.

Using the following method we can update any attribute per store view as well. This method is defined in Magento out-of-the box and can handle 1000-2000 attribute update at a time. The third parameter is the $optionId returned as above.

 

<?php 
     function massUpdateProductAttribute($storeViewId, $productId, $attributeCode, $attributeValue)
    {
        // mass update per store view
        $action = Mage::getModel('catalog/resource_product_action');
        /*$storeViewId = array($storeViewId);*/
        $action->updateAttributes(array($productId), array(
            $attributeCode => $attributeValue
        ), $storeViewId);
    }
?>

 

Cheers!

Categorized in: