I need to display product image in success page without using object manager which is bad practice.
thank you
-
You may take some help from this Click here– Zahid HSep 7, 2021 at 12:14
2 Answers
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.
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;
}
}