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?
Shopware will inject in the
onProductLoadedfunction anEntityLoadedEventobject, not aPriceobject. 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
$entityLoadedEventand then get the price: