I've problem to get current product id from custom block displayed on product page. Here my code :

class TestBlock extends BlockBase {

  public function build() {

$product = \Drupal::routeMatch()->getParameter('node');

$productid = $product->product_id();

return array(
 '#markup' => $this->t('Product ID : ') . '<h2>' . $productid . '</h2>',      



Do you have any idea to get the current ID from product ?

Thank you for your help.

2 Answers 2


Use this below code to get product ID

$product_id = \Drupal::routeMatch()->getParameter('commerce_product')->id(); 

and then return the value in custom block,

return [      
      '#product_id' =>  $product_id,
  • 1
    Careful, getParameter will return NULL if there's no product and the page will die with a fatal error when you try to use it as an object
    – Clive
    Nov 29, 2017 at 11:39
  • can we set condition for checking null values? Nov 29, 2017 at 11:41
  • Yeah of course. id() is lowercase too BTW
    – Clive
    Nov 29, 2017 at 11:47
  • It's work, thank you :) But i have now a problem with cache. Need to clear it to get the correct product id. How i can fix it ?
    – Webman
    Nov 29, 2017 at 11:49
  • ok clive, i will change it Nov 29, 2017 at 11:49

Like, such code should work:

$product_id = \Drupal::routeMatch()->getRawParameter('commerce_product');

But in my case it is not working. But it work:

$paramList = \Drupal::routeMatch()->getRawParameters();
foreach($paramList as $paramName=>$paramVal) {
    // save params to any variables...

Your Answer

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

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