Call to a member function getProductId() on a non-object?
-
16-10-2019 - |
Question
I have created custom module, In that I have just override the Mage_Catalog_Block_Product
class to get the getPrice()
. But it's returning an error Call to a member function getProductId() on a non-object?
my php code is:
//controller
<?php
class Course_Mca_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
}
//block file
<?php
class Course_Mca_Block_Products extends Mage_Catalog_Block_Product
{
public function getPrice()
{
return parent::getPrice();
}
}
//web.phtml file
<?php echo $this->getPrice() ?>
//layout.xml file
<?xml version="1.0"?>
<layout version="0.1.0">
<mca_index_index>
<reference name="content">
<block type="mca/products" name="mca_mca" template="mca/web.phtml"></block>
</reference>
</mca_index_index>
</layout>
//Course_mca.xml
<?xml version="1.0"?>
<config>
<modules>
<Course_Mca>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Catalog/>
</depends>
</Course_Mca>
</modules>
</config>
//config.xml
<blocks>
<!-- it's not working -->
<!-- <catalog>
<rewrite>
<product>Course_Mca_Block_Products</product>
</rewrite>
</catalog>-->
<!-- it's working -->
<mca>
<class>Course_Mca_Block</class>
</mca>
</blocks>
Can anyone tell me where I went wrong?
Thanks in advance.
Solution
take a look at the original getPrice
method.
It looks like this:
public function getPrice()
{
return $this->getProduct()->getPrice();
}
Digging deeper you end up in Mage_Catalog_Block_Product::getProduct()
that looks like this:
public function getProduct()
{
if (!$this->getData('product') instanceof Mage_Catalog_Model_Product) {
if ($this->getData('product')->getProductId()) {
$productId = $this->getData('product')->getProductId();
}
if ($productId) {
$product = Mage::getModel('catalog/product')->load($productId);
if ($product) {
$this->setProduct($product);
}
}
}
return $this->getData('product');
}
In your case $this->getData('product')
return null
, and since null
is not an instance of Mage_Catalog_Model_Product
you enter the first if
statement and it crashes on this line: if ($this->getData('product')->getProductId()) {
because you cannot call null->getProductId()
.
Any instance of Mage_Catalog_Block_Product
makes sense if you attach a product to it. Considering your layout file, I can conclude that you are trying to use your block without any product.
Here is how your Mca_IndexController::indexAction()
should look:
$this->loadLayout();
$block = $this->getLayout()->getBlock('mca_mca');
if ($block){
$productId = 15;//for example
$product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId);
$block->setProduct($product);
}
$this->renderLayout();