开发者

Getting Product or ProductID in magento

开发者 https://www.devze.com 2023-02-03 15:34 出处:网络
when writing a new set of .phtml & block: What is the recommanded way to know if the block is currently on a product page ?

when writing a new set of .phtml & block:

What is the recommanded way to know if the block is currently on a product page ?

If it is on a 开发者_开发技巧product page then how do I get to the data of the currently being viewed product ?

Thanks, Eyal


1st question) How to know that you're on product view page.

Your problem is not clear because you don't say the purpose of such functionality. I interpret your question as "How can my blockknow that it's embedded in Product View page and not in some other page?".

The most common way is to get layout of page and search it for standard block designed to view product. So in your block you can make following request:

$block = $this->getLayout()
    ->getBlock('product.info');

if ($block) {
    // Block exists - you're viewing product page
}


The other method is to check layout handles used to form current page layout:

$handles = $this->->getLayout()
    ->getUpdate()
    ->getHandles();
if (in_array('catalog_product_view', $handles)) {
    // Handle exists - you're viewing product page
}

However it's more concrete method, it returns positive result only when viewing product page and not pages with similar designs using product view blocks. For, example Product Review page will show you same product page with minor differences but it uses its own (not 'catalog_product_view') handle for it. As far as you said nothing about your purpose I cannot recommend you to choose first or second method.

Notice: you architecture can be wrong, because usually
a) your block either doesn't need to know where it's embedded, so it doesn't need not check currently viewed page
b) or your block is used only for product view page. But in this case it's a layout xml task to put your block only in required pages and blocks.

2nd question) How to get current product on product view page.

Use following code:

  $product = Mage::registry('current_product');

And you'll get the product currently viewed.


You can check current request object - it holds all data about module, controller, action and params which is currently in use. After that you could compare it with product page ones: does the module, controller and action the same and does product id matches

But you should aware of third-party customizations which could replace standard Magento product view controller with theirs ones


This will let you know what product is being viewed.

Mage::registry('current_product')

If there is a current_product then you are probably on a product page, although this doesn't guarantee the page is being handled by a catalog controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消