DevOPlug
DevOPlug

Reputation: 61

What Did I Do Wrong Here With Shopware 6 Product.Loaded Event

I created a bare minimum Shopware 6 plugin to display product ID when the product is loaded. It worked fine. Below is my code.

   PATH: src/Resources/config/services.xml

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        
        <service id="TestPlugin\Listener\ProductLoadedListener" >
            <tag  name="kernel.event_listener" event="product.loaded" />
        </service>

    </services>
</container>

Below is the ProductLoadedListener.php codes

PATH: src/Listener/ProductLoadedListener.php

<?php declare(strict_types=1);

namespace TestPlugin\Listener;

use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;

class ProductLoadedListener{
    


    public function onProductLoaded(EntityLoadedEvent $entityLoadedEvent){
        
        print_r($entityLoadedEvent->getIds());
    

    }

}

The above codes did the job it was created to do. So I updated the ProductLoadedListener.php codes

<?php declare(strict_types=1);

namespace TestPlugin\Listener;


use Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price;

class ProductLoadedListener{
    


    public function onProductLoaded(Price $price){
        
        print_r($price->getNet());
    

    }

}

I go an error

Argument 1 passed to TestPlugin\Listener\ProductLoadedListener::onProductLoaded() must be an instance of Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price, instance of Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent given, called in /var/www/html/vendor/symfony/event-dispatcher/EventDispatcher.php on line 270

So I am asking why I got the above error, I was expecting it to echo the net price?

Upvotes: 1

Views: 1693

Answers (1)

Paweł Napierała
Paweł Napierała

Reputation: 1755

Shopware will inject in the onProductLoaded function an EntityLoadedEvent object, not a Price object. That's why PHP throws this error.

If you want the get the price of the loaded product, then you should get the product from the $entityLoadedEvent and then get the price:

class ProductLoadedListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ProductEvents::PRODUCT_LOADED_EVENT => 'onProductLoaded'
        ];
    }

    public function onProductLoaded(EntityLoadedEvent $entityLoadedEvent)
    { 
        /** @var ProductCollection $loadedProducts */
        $loadedProducts = $event->getEntities();
        $firstProduct = $loadedProducts->first();
        $productNetPrice = $firstProduct->getPrice()->first()->getNet();
        dd($productNetPrice);
    }
}

Upvotes: 3

Related Questions