Chris
Chris

Reputation: 1400

Magento - How do I display only attributes that are assigned to products?

I have the following code, but it displays all attribute options. I want to only display those that have been assigned to a product. What would I change to do this?

  $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $id);  
  foreach ( $attribute->getSource()->getAllOptions(true) as $option){
      echo $option['label'];
  }

Upvotes: 0

Views: 1773

Answers (2)

clockworkgeek
clockworkgeek

Reputation: 37700

getAllOptions returns an array whereas we need a collection or query to work with. This first part joins that collection with the relevant attribute table, normally it's not a good idea to be doing this manually so be careful.

$entity = 'catalog_product';
/* @var $options Mage_Eav_Model_Mysql4_Entity_Attribute_Option_Collection */

$options = Mage::getResourceModel('eav/entity_attribute_option_collection')
    ->setAttributeFilter($id)
    ->setStoreFilter(0);

$options->getSelect()->join(
    array('ints'=>"{$entity}_entity_int"),
    '(ints.value=store_value.value_id) AND (ints.attribute_id=main_table.attribute_id)',
    ''
)->group('option_id');

Now you can just step through the options,

/* @var $option Mage_Eav_Model_Entity_Attribute_Option */
foreach ($options as $option) {
    echo $option->getValue();
}

...or convert to array to get back where you started.

foreach ($options->toOptionArray() as $option) {
    echo $option['label'];
}

Upvotes: 1

Oğuz Çelikdemir
Oğuz Çelikdemir

Reputation: 4980

How about this :

$product = Mage::getModel("catalog/product")->load(167);
    foreach ($product->getOptions() as $o) {

        echo "Custom Option TYPE: " . $o->getType() . "<br/>";
        echo "Custom Option TITLE: " . $o->getTitle() . "<br/>";
    } 

Upvotes: 0

Related Questions