【发布时间】:2023-01-20 18:58:12
【问题描述】:
有谁知道使用 Shopware\Storefront\Page\Product\ProductPageLoadedEvent 修改产品数据?
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="Swag\BasicExample\Service\AddDataToPage" >
<argument type="service" id="product.repository"/>
<tag name="kernel.event_subscriber" />
</service>
</services>
</container>
AddDataToPage.php
<?php declare(strict_types=1);
namespace Swag\BasicExample\Service;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
class AddDataToPage implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $productRepository;
/**
* @param EntityRepositoryInterface $productRepository
*/
public function __construct(
EntityRepositoryInterface $productRepository
)
{
$this->productRepository = $productRepository;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductsLoaded'
];
}
/**
* @param ProductPageLoadedEvent $event
* @return void
*/
public function onProductsLoaded(
ProductPageLoadedEvent $event
)
{
// the product is inside the page object
$productData = $event->getPage()->getProduct();
//modifying name
$this->log($productData->getName());
$productData->setName('Prefix Product Name' . $productData->getName());
$this->log($productData->getName());
//modifying ManufacturerNumber
$this->log($productData->getManufacturerNumber());
$productData->setManufacturerNumber('Prefix ManufacturerNumber' . $productData->getManufacturerNumber());
$this->log($productData->getManufacturerNumber());
$event->getPage()->setProduct($productData);
}
/**
* @param $message
* @return void
*/
private function log($message)
{
$logFileName = 'someFile.log';
file_put_contents(
$logFileName,
$message . PHP_EOL,
FILE_APPEND
);
}
}
修改上述更改后,它仍然显示原始数据,但
$event->getPage()->setProduct($productData);
我怀疑 ProductPageLoadedEvent 是在调度事件之后还是在调度事件之前。
【问题讨论】:
-
我已经测试了你的代码并且它有效。您甚至不必设置产品,因为
$productData是对产品对象的引用。所以你可以删除$event->getPage()->setProduct($productData);这一行。您是否检查过您的插件是否处于活动状态?你清除缓存了吗? -
是的,清除了缓存。只是为了添加进一步的更改记录到日志文件中,但不会反映在带有更改的产品详细信息页面上。也尝试过不使用
$event->getPage()->setProduct($productData);行,但没有成功。 -
您是否为产品详情页面使用自定义布局?您的html代码中是否有元素
<div class="cms-element-product-name">? -
在最近的 Shopware 版本中,产品页面有两组模板:一组是选择自定义布局,另一组是用于非自定义布局的旧版本(我相信迟早会被删除)。如果模板更改不适用,这是错误的常见原因:那么可能使用了错误的模板。这也可以通过开发工具栏进行验证。
-
你解决了吗?