How to convert an Object manager to Block?

To get the source list, I am using object manager directly in my phtml template, but I read in docs that we should not use it directly.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$sourceList = $objectManager-
>get(‘\Magento\Inventory\Model\ResourceModel\Source\Collection’);
$sourceListArr = $sourceList->load();foreach ($sourceListArr as $sourceItemName) {
$sourceCode = $sourceItemName->getSourceCode();
$sourceName = $sourceItemName->getName();
}

Solution:

create a block for fetching the source collection.

Then call the function on the template file by using the following code,

$cduObj= $block->getLayout()->createBlock(‘JJ\Sourcelist\Block\Inventory’);

$sourceListArr = $cduObj->getSource();

 foreach ($sourceListArr as $sourceItemName) {

        $sourceCode = $sourceItemName->getSourceCode();

echo $sourceCode;

    }

Leave a comment

Your email address will not be published. Required fields are marked *