Question

I am trying to load a specific virtual products with its custom options, but instead I keep getting an empty array.

My attribute is 'part_identifier' in the attribute set 'boat_part' It is a drop-down type attribute with several options. The option I am trying to pull by is 'Look'.

Here is my code:

$attribute = 'msh_boat_part_identifier';

$boatLookProducts = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter($attribute, array('like'=>'Look'))
    ->load()
    ->getItems();

foreach($boatLookProducts as $boatLookProduct)
{
    $return[] = array(
        "id" => (int)$boatLookProduct->getEntityId(),
        "name" => $boatLookProduct->getName(),
        "type" => "profile",
        "shortDesc" => $boatLookProduct->getShortDescription(),
        "desc" => $boatLookProduct->getDescription(),
        "active" => ($boatLookProduct->getStatus() === "2" ? false : true)
    );
}
echo Mage::helper('pb')->ConvertToJson($return);

In my query for the collection, if I change the array to

->addAttributeToFilter($attribute, array('like'=>'%%'))

it will successfully return all proructs, but I cant get the specific one I want!

Was it helpful?

Solution

As part_identifier is a dropdown attribute, you cannot filter the collection by the option label.

In order to filter a collection by an option, you need to get that option label's id (actual option value).

Then you can filter the collection by that option ID:

// use your own attribute code here 
$attributeCode = 'your_attribute_here';
$attributeOption = 'Look';

$attributeDetails = Mage::getSingleton('eav/config')
    ->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
$options = $attributeDetails->getSource()->getAllOptions(false); 
$selectedOptionId = false;
foreach ($options as $option){ 
    // print_r($option) and find all the elements 
    echo $option['value']; 
    echo $option['label'];
    if ($option['label'] == $attributeOption) {
        $selectedOptionId = $option['value'];   
    }
}

if ($selectedOptionId) {
    $products = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter($attributeCode, array('eq' => $selectedOptionId))
}

OTHER TIPS

This is late and maybe not even valid at the time of asking, though I found a more concise way by doing:

$attributeOptionId = Mage::getSingleton('eav/config')
   ->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'your_attribute_code')
   ->getSource()
   ->getOptionId('Option Text Value/Label');

Then you use it in the collection filter as usual

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top