Question

I'm trying to do something like this.

function clientname_preprocess_commerce_product(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  // Get the product variations and store them in $variations.
  if (!empty($variations)) {
    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */
    $variation = reset($variations);
    /** @var \Drupal\commerce_product\ProductVariationFieldRendererInterface $variation_renderer */
    $variation_renderer = \Drupal::service('commerce_product.variation_field_renderer');
    // Override the variation list price with the price of the variation.
    $product['variation_list_price'] = $variation_renderer->renderField('list_price', $variation);
  }
}

I am not sure how to get the product variations in hook_preprocess_commerce_product().

What code should I use to get the product variations and store them in $variations?

Was it helpful?

Solution

  $product = $variables['elements']['#commerce_product'];

  $variations = $product->getVariations();     

  foreach ($variations as $variation){    
      $list_price = $variation->getListPrice();
    // Do something with the variation list price here...
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top