简体   繁体   中英

Rewrite Magento catalog product view action

I write an extension for ProductController, I need to make a redirect to canonical URL when there is a request for /catalog/product/view/[ID-PROD] URL. I create a module with this config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <MyModule_CanonicalRedirect>
            <version>0.0.0.0.1</version>
        </MyModule_CanonicalRedirect>
    </modules>


    <frontend>
        <routers>
            <MyModule_canonicalredirect>
                <use>standard</use>
                <args>
                    <modules>
                        <MyModule_CanonicalRedirect>MyModule_CanonicalRedirect
                        </MyModule_CanonicalRedirect>
                    </modules>
                    <frontName>canonicalredirect</frontName>
                </args>
            </MyModule_canonicalredirect>
        </routers>
    </frontend>


    <global>
        <rewrite>
            <MyModule_CanonicalRedirect>
                <from><![CDATA[#^/catalog/product/view/#]]></from>
                <to>/canonicalredirect/index/view/</to>
            </MyModule_CanonicalRedirect>
        </rewrite>
    </global>
</config>

and this is my controller:

include_once('Mage/Catalog/controllers/ProductController.php');
class MyModule_CanonicalRedirect_IndexController extends Mage_Catalog_ProductController {
    public function viewAction()
    {
        // Get initial data from request
        $categoryId = (int) $this->getRequest()->getParam('category', false);
        $productId  = (int) $this->getRequest()->getParam('id');
        $specifyOptions = $this->getRequest()->getParam('options');

        $prod = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId);


        if($prod->getId() == $productId) {
            $prodUrl = $prod->getUrlModel()->getUrl($prod, array('_ignore_category'=>true));
            Mage::app()->getFrontController()->getResponse()->setRedirect($prodUrl, 301);
        }
        else {
            parent::viewAction();
        }
    }
}

When I try to get a existing product, all is ok, but if I try to get a product with an ID that does not exist I have the error:

Call to a member function getMetaTitle() on a non-object in /app/code/core/Mage/Catalog/Block/Product/View.php on line 56

I find more question about this error but, in my case there is a simple forward to NOROUTE action, I can't init the product because I haven't it.

Please reply me for this issue. Thanks in advance.

是的,您必须首先在操作中加载产品并在注册表中设置产品对象,这将解决您的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM