6

I have a small import script that will import product to Magento 1.

It works well but there is something not work.If a product attribute happen to be a select type attribute the value will not save. I can determine this cause through eav system and magento would like to have the option id and not text value.

I have:

$product->setColour('red')->save();

But magento want:

$product->setColour(22)->save();

Is a method in magento that will accept the text value and correctly set the option id in the background for me?

2 Answers 2

11

This is untested but should work:

$colourId = $product->getResource()->getAttribute("colour")->getSource()->getOptionId("red");
$product->setColour($colourId)->save();
1
  • It works. Very nice . Commented Sep 27, 2016 at 11:39
2

You can do it by using below mentioned code:

<?php
$attrId = attributeValueExists('color', 'red');
$product->setData('color', $attrId);
$product->save();

function attributeValueExists($argAttribute, $argValue)
{
    $attributeModel        = Mage::getModel('eav/entity_attribute');
    $attributeOptionsModel = Mage::getModel('eav/entity_attribute_source_table') ;

    $attributeCode         = $attributeModel->getIdByCode('catalog_product', $argAttribute);
    $attribute             = $attributeModel->load($attributeCode);

    $options               = $attributeOptionsModel->getAllOptions(false);

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

    return false;
}

Just use attributeValueExists('attribute_code','attribute text value') this function in your code.Hope it will help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.