0

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;
4
  • $block->getImage($_item, $image) returns null. that's what the exception tells you Jun 14, 2019 at 11:28
  • add getImage() function code Jun 14, 2019 at 11:34
  • can u place that code??
    – Waqar Ali
    Jun 14, 2019 at 11:36
  • check my answer Jun 14, 2019 at 11:44

1 Answer 1

2

.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();
    }
}
10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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