Search code examples
shopwareshopware6shopware6-app

How to show parent product number on listing page in Shopware 6?


I want to show the parent product number of variant products on the listing page.
But I have no idea how to do it.
Can anyone help me with this?


Solution

    • Add a subscriber for the listing result events.
    • Fetch key value pairs from variant IDs to parent product number.
    • Use the key value pairs to set an extension to the affected product objects.
    • In your product box template print the content of the extension.

    Service definition:

    <service id="MyPlugin\Subscriber\CustomListingSubscriber">
        <tag name="kernel.event_subscriber"/>
        <argument type="service" id="Doctrine\DBAL\Connection"/>
    </service>
    

    Subscriber:

    class CustomListingSubscriber implements EventSubscriberInterface
    {
        private Connection $connection;
    
        public function __construct(Connection $connection)
        {
            $this->connection = $connection;
        }
    
        public static function getSubscribedEvents(): array
        {
            return [
                ProductListingResultEvent::class => [
                    ['handleListingResult', 0],
                ],
                ProductSearchResultEvent::class => [
                    ['handleListingResult', 0],
                ],
            ];
        }
    
        public function handleListingResult(ProductListingResultEvent $event): void
        {
            $ids = $event->getResult()->getEntities()->getIds();
    
            $sql = 'SELECT LOWER(HEX(p.id)), pp.product_number
                    FROM product p
                    INNER JOIN product pp ON pp.id = p.parent_id AND pp.version_id = :version
                    WHERE p.id IN (:ids) AND p.version_id = :version';
    
            $mapping = $this->connection->fetchAllKeyValue(
                $sql,
                ['ids' => Uuid::fromHexToBytesList($ids), 'version' => Uuid::fromHexToBytes(Defaults::LIVE_VERSION)],
                ['ids' => Connection::PARAM_STR_ARRAY]
            );
    
            foreach ($mapping as $variantId => $parentProductNumber) {
                $product = $event->getResult()->getEntities()->get($variantId);
    
                if (!$product instanceof ProductEntity) {
                    continue;
                }
    
                $extension = new TextStruct();
                $extension->setContent($parentProductNumber);
                $product->addExtension('parentProductNumber', $extension);
            }
        }
    }
    

    Twig template:

    {{ product.extensions.parentProductNumber.content }}