1

Magento 2.3.5 How to set child product image from URL for configurable product on the product detail page

Example - product URL is - http://xyx.com/product.html#447=5439

dropdown is selecting according to attributes and with their values but the image is not updating

How can we show children product images based on their attributes and their values?

0

Get Product Small Image Url Using Product id. You can retrieve small_image Url of the product.

You need to instantiate the ImageFactory to load image objects using Magento\Catalog\Helper\ImageFactory.

Check the code snippet to retrieve Image Url,

namespace Jesadiya\ProductSmallImage\Model;

use Exception; use Psr\Log\LoggerInterface; use Magento\Catalog\Helper\ImageFactory; use Magento\Catalog\Api\ProductRepositoryInterface;

class ImageUrl { /** * Small image value. * * @var string */ const SMALL_IMAGE = 'small_image';

/**
 * @var ImageFactory
 */
public $imageFactory;

/**
 * @var LoggerInterface
 */
public $logger;

public function __construct(
    ImageFactory $imageFactory,
    ProductRepositoryInterface $productRepository,
    LoggerInterface $logger
) {
    $this->imageFactory = $imageFactory;
    $this->productRepository = $productRepository;
    $this->logger = $logger;
}

/**
 * Get Image url
 *
 * @return string
 */
public function getImageUrl()
{
    $productId = 1;
    $imageUrl = null;
    try {
        $product = $this->productRepository->getById($productId);
        if ($product) {
            $imageHelper = $this->imageFactory->create()->init($product, self::SMALL_IMAGE);
            $imageUrl = $imageHelper->getUrl();
        }
    } catch (Exception $exception) {
        $this->logger->error($exception->getMessage());
    }

    return $imageUrl;
}

} You can get Product small_image URL by product id by referring the above code.

1
  • actually i am looking solution for this using jquery or javascript – sumeet bajaj Apr 5 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.