balanv
balanv

Reputation: 10898

How to get all active attributes of products in Magento?

I am working in a new "Filter by Product" module in Magento, i have a situation where i should retrieve all attributes and their values. I Googled this and found the below code

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

$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
      ->setEntityTypeFilter($product->getResource()->getTypeId())
      ->load();

      //      ->addFieldToFilter('attribute_code', 'color') 

$attribute = $attributes->getFirstItem()->setEntity($product->getResource());

/* @var $attribute Mage_Eav_Model_Entity_Attribute */

$attr = $attribute->getSource()->getAllOptions(true);

foreach ($attr as $att) {
    echo " Label : ".$att['label']." Value : ".$att['value']."";
}
 

but this retrieves only the label and value of last attribute from list of all available attributes.

how to i get all the attributes? what am i doing wrong in this code?

Thanks, Balan

Upvotes: 3

Views: 11802

Answers (2)

Vinai
Vinai

Reputation: 14182

Try this:

$attributes = Mage::getSingleton('eav/config')
    ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection();

// Localize attribute label (if you need it)
$attributes->addStoreLabel(Mage::app()->getStore()->getId());

// Loop over all attributes
foreach ($attributes as $attr) {
    /* @var $attr Mage_Eav_Model_Entity_Attribute */
    // get the store label value
    $label = $attr->getStoreLabel() ? $attr->getStoreLabel() : $attr->getFrontendLabel();
    echo "Attribute: {$label}\n";

    // If it is an attribute with predefined values
    if ($attr->usesSource()) {

        // Get all option values ans labels
        $options = $attr->getSource()->getAllOptions();

        // Output all option labels and values
        foreach ($options as $option)
        {
            echo "    {$option['label']} (Value {$option['value']})\n";
        }
    }
    else
    {
        // Just for clarification of the debug code
        echo "    No select or multiselect attribute\n";
    }
}

Upvotes: 16

Alexandre
Alexandre

Reputation: 3170

This is the first solution:

 $products = Mage::getModel('catalog/product')->getCollection();
 foreach($this->products as $product) {
   $prod = Mage::getModel('catalog/product')->load($product->getId());
 }

If you are using using the data from outside magento, you can use a class I made: http://blog.alexparadise.com/magento-dbeav-class/

It's beta but that should work in your case. Or get the concept of the EAV table... and make your own SQL query.

Upvotes: 0

Related Questions