How to check if an attribute exists in a product attribute? Magento

How to check if an attribute exists in a product attribute?

I need to know if a product has an attribute for its set of attributes.

I get the attribute with:

$attrPricekg = Mage::getModel('catalog/product')->load($_product->getId())->getPricekg(); 

If the attribute exists in the product attribute set, the display is $ attrPricekg: set value for the product, or 0 if no value is set for the product.

If the attribute does not exist in the product attribute set, the value $ attrPricekg 0 is displayed. This is my problem. I need to avoid this, I want to verify that the attribute does not exist for this product.

Thanks.

+7
source share
4 answers

EDIT: This is not the correct answer.

 $product->offsetExists('pricekg'); 

See Varien_Object::offsetExists() (link) .

-3
source

Now I will give an answer that works independently!

 $product = Mage::getModel('catalog/product')->load(16); $eavConfig = Mage::getModel('eav/config'); /* @var $eavConfig Mage_Eav_Model_Config */ $attributes = $eavConfig->getEntityAttributeCodes( Mage_Catalog_Model_Product::ENTITY, $product ); if (in_array('pricekg',$attributes)) { // your logic } 
+27
source

To check if a specific attribute exists in a product, it must return true, even if the attribute is null.

One of the methods:

 $attr = Mage::getModel('catalog/resource_eav_attribute')->loadByCode('catalog_product',$code); if (null!==$attr->getId()) 

{// attribute code exists here}

You can, of course, also write to one line:

 if(null!===Mage::getModel('catalog/resource_eav_attribute')->loadByCode('catalog_product','attributecode_to_look_for')->getId()) { //'attributecode_to_look_for' exists code here } 

Found and changed a bit: https://github.com/astorm/Pulsestorm/issues/3

+6
source

Maybe this is the best for you:

 $attribute = Mage::getModel('catalog/product')->load($productId)->getResource()->getAttribute($attributeCode); if ($attribute && $attribute->getId()) { ... } 

You can also try

 $attributes = $product->getAttributes(); 

But you can check everything in the attribute collection:

 $entityTypeId = Mage::getModel('eav/entity') ->setType('catalog_product') ->getTypeId(); $attributeId = 5; $attributeSetName = 'Default'; $attributeSetId = Mage::getModel('eav/entity_attribute') ->getCollection() ->addFieldToFilter('entity_type_id', $entityTypeId) ->addFieldToFilter('attribute_set_name', $attributeSetName) ->addFieldToFilter('attribute_id', $attributeId) ->getFirstItem(); 

Maybe the source code needs some corrections, but I think you will understand this idea.

See a few more examples, also - http://www.blog.magepsycho.com/playing-with-attribute-set-in-magento/

0
source

All Articles