How do I show Product Variations on the product listing page?
Product Variation - ProductListingSubscriber
I have created the ProductListingSubscriber.php in the Subscriber folder.
<?php declare(strict_types=1);
namespace Prateeksha\HelloWorld\Subscriber;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Content\Product\SalesChannel\Sorting\ProductSortingCollection;
use Shopware\Core\Content\Product\SalesChannel\Sorting\ProductSortingEntity;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductListingSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
ProductListingCriteriaEvent::class => 'onProductListingCriteria'
];
}
public function onProductListingCriteria(ProductListingCriteriaEvent $event)
{
$criteria = $event->getCriteria();
// Add associations to load variants
$criteria->addAssociation('options');
$criteria->addAssociation('children');
$criteria->addAssociation('variation');
}
}
- I have added this in the services.xml
<service id="Prateeksha\HelloWorld\Subscriber\ProductListingSubscriber">
<tag name="kernel.event_subscriber"/>
</service>
- in this file views/storefront/component/product/card/box-standard.html.twig
{% sw_extends '@Storefront/storefront/component/product/card/box-standard.html.twig' %}
{% block component_product_box_content %}
{{ parent() }}
{# Check if the product has children (variants) #}
{% if product.children and product.children.count > 0 %}
<div class="product-variants">
<select class="variant-selector" onchange="location = this.value;">
{# Loop through each child (variant) #}
{% for child in product.children %}
{% set variantOption = '' %}
{% for option in child.options %}
{% set variantOption = variantOption ~ option.group.translated.name ~ ': ' ~ option.translated.name ~ ' ' %}
{% endfor %}
<option value="{{ seoUrl('frontend.detail.page', {'productId': child.id}) }}">
{{ variantOption }}
</option>
{% endfor %}
</select>
</div>
{% endif %}
{% endblock %}
kindly guide me…