I got Drupal 8 / Commerce 2 installation, and trying to create product category pages, showing product image, title and price range (min & max price)
I've created product category page with Views. Category is defined as Taxonomy reference field in product. Views has "Contextual filter", where category name is taken from url e.g. /product/[category].
Product catalog page works fine, showing fields defined in (custom) Summary view mode. It shows title and the first product variation image and price.
Only thing missing is the price range info
I've tried to do some experiments by
overwriting commerce-product.html.twig in custom theme
writing hook__preprocess_commerce_product in custom module
..but with no luck. Debugging is hard because, for some reason kint() / dpm() calls fail or just take tooo long and give execution time out...
So the question is: how and where to check product variations lowest & highest prices plus pass them to product template?
Any hints or ideas are greatly appreciated.
EDIT:
I got it done by adding the following preprocess hook to my custom module
function CUSTOMMODULE_preprocess_commerce_product(&$variables) {
$product = $variables['elements']['#commerce_product'];
foreach( $product->variations as $variation) {
$prices[] = $variation->entity->getPrice()->getNumber();
}
$min_price = min($prices);
$max_price = max($prices);
if ($min_price != $max_price) {
$variables['min_price'] = $min_price;
$variables['max_price'] = $max_price;
}
$variables['currency'] = $variation->entity->getPrice()->getCurrencyCode();
}
... And then in commerce-product--teaser.html.twig
{% if min_price is defined and max_price is defined %}
{{ min_price |number_format(2, '.', ',') }} -
{{ max_price |number_format(2, '.', ',') }} {{ currency }}
{% else %}
{{ product.price }}
{% endif %}