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 Answer 1

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();
5
  • Thanks for the quick answer, is there anything else I need to do, as both are empty.
    – Aravona
    Commented Nov 3, 2016 at 10:46
  • @Aravona no that's definitely the only thing you need to do. Flush the cache and remove var/generation Commented Nov 3, 2016 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
    Commented Nov 3, 2016 at 10:50
  • you need not to define block because Magento replace $this with $block , So now you can use $block in template file. Commented Nov 3, 2016 at 11:31
  • Finally got it working.... now it's just the rest of the code that's broken! :)
    – Aravona
    Commented Nov 3, 2016 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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