Magento – Create attribute option if not exists

attributeseavproductproduct-attribute

How would i create a dropdown attribute option if it does not already exist for an attribute?

For example, the following will not work correctly if the option values do not exist:

$productColors = array('sku_1' => 'red','sku_2' => 'blue','sku_3' => 'green');

foreach($productColors as $sku => $color) {
    $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);

    $product->setData('color', $color)->save(); // This wont work if that option value is not alaready created

}

I now need a way to ensure the value is set properly

Best Answer

You would need to check the attribute for the option you are adding, and if it doesn't exist, add it using Mage_Eav_Model_Entity_Setup.

<?php

foreach($productColors as $sku => $color) {

    addAttributeValue('color', $color);

}

function addAttributeValue($attributeCode, $attValue) {

    if (!attributeValueExists($attributeCode, $attValue)) {
        $attr_model = Mage::getModel('catalog/resource_eav_attribute');
        $attr = $attr_model->loadByCode('catalog_product', $attributeCode);
        $attr_id = $attr->getAttributeId();
        $option['attribute_id'] = $attr_id;
        $option['value']['option_name'][0] = $attValue;
        $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
        $setup->addAttributeOption($option);
    }
}

function attributeValueExists($attribute, $value) {
    $attribute_model = Mage::getModel('eav/entity_attribute');
    $attribute_options_model = Mage::getModel('eav/entity_attribute_source_table');
    $attribute_code = $attribute_model->getIdByCode('catalog_product', $attribute);
    $attribute = $attribute_model->load($attribute_code);
    $attribute_options_model->setAttribute($attribute);
    $options = $attribute_options_model->getAllOptions(false);

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

This may need some tweaking for your particular situation, but the general idea works.

Related Topic