如果您正确创建了实体(Sylius 方式),则应该有一个事件可以触发。您需要将实体定义为资源:
# config/packages/sylius_resource.yaml
sylius_resource:
resources:
app.name_of_etity:
driver: doctrine/orm
classes:
model: App\Entity\NameOfEntity
如果您这样定义资源,则事件将是:
event: app.system_manual.pre_create
event: app.app.name_of_entity.pre_update
按照本指南:
https://docs.sylius.com/en/1.6/cookbook/entities/custom-model.html
更新
因为您正在通过现有产品表单管理您的自定义实体,所以上述内容将不起作用。要使其工作,您可以创建自己的事件侦听器。
final class ProductSeoTranslationImagesUploadListener
{
/** @var ImageUploaderInterface */
private $uploader;
public function __construct(ImageUploaderInterface $uploader)
{
$this->uploader = $uploader;
}
public function uploadImages(GenericEvent $event): void
{
$subject = $event->getSubject();
// Add a ProductSeoInterface so you can use this check:
Assert::isInstanceOf($subject, ProductSeoInterface::class);
foreach ($subject->getSeo()->getTranslations() as $translation) {
Assert::isInstanceOf($translation, ImagesAwareInterface::class);
$this->uploadSubjectImages($translation);
}
}
private function uploadSubjectImages(ImagesAwareInterface $subject): void
{
$images = $subject->getImages();
foreach ($images as $image) {
if ($image->hasFile()) {
$this->uploader->upload($image);
}
// Upload failed? Let's remove that image.
if (null === $image->getPath()) {
$images->removeElement($image);
}
}
}
}
提示:创建(产品)SeoInterface,以便您可以执行类型检查。
别忘了注册eventListener:
App\EventListener\ProductSeoTranslationImagesUploadListener:
tags:
- {
name: kernel.event_listener,
event: sylius.product.pre_create,
method: uploadImages,
}
- {
name: kernel.event_listener,
event: sylius.product.pre_update,
method: uploadImages,
}