Magento2 – Call to a Member Function toHtml() on Null

magento2PHP

enter image description here I am trying to show Product Collection in .phtml file of custom module

<a href="<?= /* @escapeNotVerified */ $block->getProductUrl($_item) ?>" class="product photo product-item-photo">
    <?= $block->getImage($_item, $image)->toHtml() ?>
</a>

in this line i am getting error as

Fatal error: Uncaught Error: Call to a member function toHtml() on
null

anyone please help

i got product Collection By Product ID

$this->_itemCollection=[];
        foreach ($collection as $value) {
            $product = $this->_productRepository->getById($value->getProductId());
            array_push($this->_itemCollection, $product);
        }     
        return $this;

Best Answer

.phtml file

<a href="<?= /* @escapeNotVerified */ $block->getProductUrl($_item) ?>" class="product photo product-item-photo">
                                <?= $this->getImage($_item, $image)->toHtml() ?>
</a>

getImage() Function in Block File

 <?php

namespace Vendor\Module\Block;

class file_name extends Template
{
    protected $imageBuilder;

    public function __construct(
        \Magento\Catalog\Block\Product\Context $contextImage,
        array $data = []
    )
    {
        $this->imageBuilder = $contextImage->getImageBuilder();
        parent::__construct($context, $data);
    }
    public function getImage($product, $imageId, $attributes = [])
    {
        return $this->imageBuilder->setProduct($product)
            ->setImageId($imageId)
            ->setAttributes($attributes)
            ->create();
    }
}