0

I need to display product image in success page without using object manager which is bad practice.
thank you

1
0

You can use the Helper Image to achieve that:

in your PHTML

/** @var Magento\Catalog\Helper\Image $_helperImage */

$_helperImage = $this->helper('Magento\Catalog\Helper\Image');

$items = GET THE ITEMS IN THE ORDER
$product = $item->getProduct();

$producImg = $_helperImage->init($product, 'small_image')->setImageFile($product->getSmallImage())->resize(100, 100)->getUrl();

That way, you can get the Image URL of the current product in your order.

1
  • Unfortunately not working
    – sara ben
    Sep 9 '21 at 15:28
0

Find the below code for fetch product small image-based on product id.

<?php

namespace Vendor\Mymodule\Block;

use Exception;
use Psr\Log\LoggerInterface;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Helper\ImageFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;


class customImage extends Template
{

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

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

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

    public function __construct(
            Template\Context $context,
            ImageFactory $imageFactory,
            ProductRepositoryInterface $productRepository,
            LoggerInterface $logger,            
            array $data = array()
    ) {
        $this->imageFactory = $imageFactory;
        $this->productRepository = $productRepository;
        $this->logger = $logger;
        parent::__construct($context, $data);
    }

    /**
     * Get Product Image url
     * @param productId
     * @return string
     */
    public function getImageUrl($productId) // Pass product id here.
    {
        $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;
    }
}

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.