Question

I've a requirement to show attribute labels in URL to filter products. I'm able to generate Url with attribute labels. Now all I've to do is convert attribute label to attribute id/value (ex: 1,2), so that code behind the scene works as it is (based on attribute value/id).

Within apply() function of app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php I'm getting attribute label in $filter = $request->getParam($this->_requestVar); (ex: Blue).

How I can convert this attribute label to attribute id (say for green it's 2), so that I can pass it to $this->_getResource()->applyFilterToCollection($this, $filter); and backend functionality will work as it is? I've tried $filter->getId(), $filter->getValue() but it doesn't work.

Is it possible to get attribute value/id from attribute label?

Was it helpful?

Solution

Get attribute value/id from attribute text/label:

$attr = 'your_attribute';
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attr);
if ($attr->usesSource()) {
    echo $color_id = $attr->getSource()->getOptionId("Purple");
}

OTHER TIPS

There's not really a simple method to call that does that but this should do the trick

$attribute = Mage::getModel('eav/entity_attribute')->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'color');

$values = Mage::getResourceModel('eav/entity_attribute_option_collection')
    ->setAttributeFilter($attribute->getId())
    ->addFieldToFilter('tsv.value', 'Bleu')
    ->setStoreFilter(Mage::app()->getStore()->getId(), false)
    ->addFieldToSelect('option_id');
$values->getSelect()->limit(1);

var_dump($values->getFirstItem()->getId());

Note that the value has to be exactly the same as the label, so including capital letters etc.

Get attribute option value

 getOptionvalue('your attribute code like color','your attribute label like blue');

    function getOptionvalue($arg_attribute, $arg_value) 
        {
            $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $arg_attribute);

            foreach ( $attribute->getSource()->getAllOptions(true, true) as $option )
            {

                if($arg_value == $option['label'])
                {

                    unset($attribute);
                    return $option['value'] ; 
                }
            }
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top