Magento阻止重写无法正常工作

时间:2014-10-11 08:15:33

标签: magento

我正在尝试重写product_new块。目的是我想添加category_id字段并仅获取一个类别的新产品。这是代码

应用\代码\本地\富\酒吧\块\产品\ New.php

class Foo_Bar_Block_Product_New扩展Mage_Catalog_Block_Product_New {

protected function _beforeToHtml()
{
  //  echo "aaaaaaasdfa";

    $todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);

    $collection = Mage::getResourceModel('catalog/product_collection');
    $collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());

    $collection = $this->_addProductAttributesAndPrices($collection)
        ->addStoreFilter()
        ->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate))
        ->addAttributeToFilter('news_to_date', array('or'=> array(
            0 => array('date' => true, 'from' => $todayDate),
            1 => array('is' => new Zend_Db_Expr('null')))
        ), 'left')
        ->addAttributeToSort('news_from_date', 'desc')
        ->setPageSize($this->getProductsCount())
        ->setCurPage(1)
    ;

  if($categoryId=$this->getData('category_id')){
    $category = Mage::getModel('catalog/category')->load($categoryId);
    $collection->addCategoryFilter($category);
  }


    $this->setProductCollection($collection);
    return parent::_beforeToHtml();
}

}

使用以下代码

在local.xml中添加了块
        <block type="foo_bar/product_new" name="new_products_list" template="catalog/product/new.phtml">
            <action method="setCategoryId"><category_id>4</category_id></action>
            <action method="setColumnCount"><columns>4</columns></action>

        </block>

模块的config.xml是

<global>
<blocks>
    <catalog>
        <rewrite>
    <product_new>Foo_Bar_Block_Product_New</product_new>
        </rewrite>
</catalog>
</blocks>
</global>

请指导我在哪里犯错误

由于

1 个答案:

答案 0 :(得分:4)

问题出在parent :: _ beforeToHtml();声明它将调用父类的_beforeToHtml方法,即Mage_Catalog_Block_Product_New。因此父函数将覆盖您已设置的集合。

解决方案:

替换:

parent::_beforeToHtml();

到:

Mage_Catalog_Block_Product_Abstract::_beforeToHtml();