How to Get ID of Custom Attribute by Text Value in Magento

attributeseav

I want to update a custom attribute and I can do that like this:

$product = Mage::getModel('catalog/product')
    ->loadByAttribute('sku',"mysku");

$product->addAttributeUpdate('manufacturer', 281);
echo $product->getAttributeText('manufacturer');

In addAttributeUpdate() instead of passing 281 which is the ID
I only have an attribute text so I should get the ID of that attribute text and insert it in the place of 281

How can I do that?

$attrtext = 'myatttext';
$product->addAttributeUpdate('manufacturer', $attrtext->getId() /* ???????? */);

Best Answer

In order for you to achieve what you're looking for, implement the following code:

// attribute code
$attribute_code = 'manufacturer';

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

// load attribute by attribute code
$attribute = $productModel->getResource()->getAttribute($attribute_code);

// load product by sku 
$product = $productModel->loadByAttribute('sku', 'mysku');

// Validate attribute
if ($attribute->usesSource()) { 
    // load option Id by value text
    $attribute_value_id = $attribute->getSource()->getOptionId('myatttext'); 

    // update product attribute
    $product->addAttributeUpdate($attribute_code, $attribute_value_id);

    echo $product->getAttributeText($attribute_code);
}

I hope this is what you're looking for.

Related Topic