1

If I have the following code in a CMS page to call a template:

{{block class="Magento\Framework\View\Element\Template" name="gifts" template="Magento_Theme::html/gifts.phtml" product_id="68"}}'

How would I then retrieve the product ID in the phtml file?

I've tried:

$product = $this->getData('product_id');

But it returns empty, what is the correct way to retrieve this variable in Magento 2?

1

It's because you're using Magento 1 syntax via $this. In Magento 2 you should use $block

You can get the data by calling:

$product = $block->getData('product_id');

Or

$product = $block->getProductId();
  • Thanks for the quick answer, is there anything else I need to do, as both are empty. – Aravona Nov 3 '16 at 10:46
  • @Aravona no that's definitely the only thing you need to do. Flush the cache and remove var/generation – Raphael at Digital Pianism Nov 3 '16 at 10:49
  • Caching isn't turned on, as this is a development version of the website. Is there anything I need to do to initiate $block? – Aravona Nov 3 '16 at 10:50
  • you need not to define block because Magento replace $this with $block , So now you can use $block in template file. – Ronak Chauhan Nov 3 '16 at 11:31
  • Finally got it working.... now it's just the rest of the code that's broken! :) – Aravona Nov 3 '16 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.