I’ve been working on a module that adds Configurable Child Products to Cart at the Simple Product they are. This all works fine.
The part of the module I’m working on now is to get the Child Product Image. If there is no Child Product Image, then to use the Parent Configurable Image instead.
This does work. But it only works for Configurable Child Products once I have uploaded an image to them (any image) and then removed it. It then inherits the Configurable Product Image correctly.
If I create a Configurable Child Product and don’t upload an image and then delete it first, it just takes the image from another product in the Cart
Please can anyone help me figure why it is working this way? Thank you.
<?php
namespace ConfigurableProductsHelper;
use MagentoFrameworkAppHelperContext;
use MagentoCatalogHelperImage;
use MagentoStoreModelStoreManagerInterface;
use MagentoFrameworkAppHelperAbstractHelper;
use MagentoCatalogModelProduct;
class Data extends AbstractHelper
{
/** @var MagentoFrameworkObjectManagerInterface * */
private $objectManager;
/** @param MagentoFrameworkObjectManagerInterface $objectmanager * */
protected $productModel;
public function __construct(
Context $context,
Product $productModel,
private readonly StoreManagerInterface $storeManager,
private readonly Image $imageHelper,
MagentoFrameworkObjectManagerInterface $objectmanager
)
{
$this->productModel = $productModel;
$this->objectManager = $objectmanager;
parent::__construct($context);
}
public function getImage($productId) {
$product = $this->productModel->load($productId);
$productId = $product->getId();
$productimage = $this->imageHelper->init($product, 'cart_page_product_thumbnail')->getUrl();
$configurableProductResource = $this->objectManager->create('MagentoConfigurableProductModelResourceModelProductTypeConfigurable');
// Get the parent product IDs for the given child product
$parentIds = $configurableProductResource->getParentIdsByChild($productId);
// If Product is part of Configurable (Has Configurable Parent)
if (isset($parentIds[0])) {
$parentProductId = $parentIds[0];
// Load the parent product
$productRepository = $this->objectManager->get('MagentoCatalogApiProductRepositoryInterface');
$parentProduct = $productRepository->getById($parentProductId);
// Get the parent product's image
$childimageUrl = $this->imageHelper->init($product, 'cart_page_product_thumbnail')->getUrl();
$parentimageUrl = $this->imageHelper->init($parentProduct, 'cart_page_product_thumbnail')->getUrl();
// if Child Image Exists, Show it
if ($product->getImage() && $product->getImage() != 'no_selection') {
$imageUrl = $childimageUrl;
}
// Show Configurable Parent Image
else {
$imageUrl = $parentimageUrl;
}
}
// Normal Product Image (not a Child Product of a Configurable Product)
else {
$imageUrl = $productimage;
}
return $imageUrl;
}
}