I am changing the image of a product from an external URL at runtime on saleschannel.product.load event. This all works fine, but when placing the order, it gives the error about
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`sv3_dev`.`order_line_item`, CONSTRAINT `fk.order_line_item.cover_id` FOREIGN KEY (`cover_id`) REFERENCES `media` (`id`) ON UPDATE CASCADE)
I am guessing it is because I am overrwriting the media entity of the product with my custom implementation like this, so it does not find the media cover ID when inserting the order line item:
$pathInfo = pathinfo($url);
$media = new MediaEntity();
$media->setId(Uuid::randomHex());
$media->setUrl($url);
$media->setMimeType(sprintf('image/%s', $pathInfo['extension']));
$media->setFileExtension($pathInfo['extension']);
$media->setFileName($pathInfo['filename']);
$productMediaEntity = new ProductMediaEntity();
$productMediaEntity->setId(Uuid::randomHex());
$productMediaEntity->setMedia($media);
$productMediaEntity->setPosition(0);
$mediaCollection = new ProductMediaCollection([$productMediaEntity]);
$entity->setMedia($mediaCollection);
if ($entity->getCover() === null) {
$entity->setCover($productMediaEntity);
} else {
$entity->getCover()->setMedia($productMediaEntity->getMedia());
}
Is there a way to dynamically change the image at run time everywhere in the storefront?
I cannot save the image / media in the filesystem due to some copyright clause which does not allow the images to be downloaded in the shop. We can only load it at runtime.
To anyone else who stumbles upon this, dynamically adding the media entity like mentioned in the question works for the rest of the shop except when placing the order, as it requires a media ID due to FK
constraint. So what I did was that I created a media
entity from the mediaRepository
and used that ID as reference for the order instead of the Uuid::randomHex()
without saving the actual image in the filesystem.