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.
Best Answer
take a look at the original
getPrice
method.It looks like this:
Digging deeper you end up in
Mage_Catalog_Block_Product::getProduct()
that looks like this:In your case
$this->getData('product')
returnnull
, and sincenull
is not an instance ofMage_Catalog_Model_Product
you enter the firstif
statement and it crashes on this line:if ($this->getData('product')->getProductId()) {
because you cannot callnull->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: