Magento – Fatal Error: Call to a Member Function getId() on a Non-Object

attributes

I am trying to get custom attribute value in frontend

I am trying below code in view.phtml , its working fine.

when i used the same code in other .phtml file its giving error :

Fatal error: Call to a member function getId() on a non-object in

<?php 

$product_id = Mage::registry('current_product')->getId();
$_product=Mage::getModel('catalog/product')->load($product_id);
$attribute = $_product->getResource()->getAttribute('cod_available');
if ($attribute)
{
    echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
?>

Best Answer

Replace your code from:

<?php 

$product_id = Mage::registry('current_product')->getId();
$_product=Mage::getModel('catalog/product')->load($product_id);
$attribute = $_product->getResource()->getAttribute('cod_available');
if ($attribute)
{
    echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
?>

To:

view.phtml

<?php 
$currentProduct = Mage::registry('current_product');
if($currentProduct) {
    $attribute = $currentProduct->getResource()->getAttribute('cod_available');
    if ($attribute) {
        echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
    }
}
?>

other .phtml (But must be available getproduct() function in block file)

<?php 

$product = $this->getProduct();
if($product->getId()) {
    $attribute = $product->getResource()->getAttribute('cod_available');
    if ($attribute) {
        echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
    }
}
?>