Magento – Magento 2 get custom module data in theme phtml

collection;magento2magento2.1.5moduleresource-model

I have created the custom module and inserted all the required fields detail in the database. Now, I want to list all rows in below file path:

I have tried with the $objectManager, but direct call $objectManager in phtml file is not correct way.

Before post this question I have go through the below answers, but when I run I getting a blank screen.

How can i get collection of custom module in magento 2

Magento 2 : How to get custom module collection in module template file

app\design\frontend\Vendor\Theme\Magento_Theme\templates\html/home_page.phtml

<div class="" data-section-name="home">
  <div class="header-section">
    <?php $collection = $block->getCustomoptionmanagerList();
        echo '<pre>'; print_r($collection); die;
    ?>

  </div>
</div>

  <div class="back-top-button"><a href="javascript:void(0)"><i class="top-arrow"></i> TOP</a></div>

Model Class code file

app\code\Vendor\Customoptionmanager\Model/Customoptionmanager.php

<?php

namespace Vendor\Customoptionmanager\Model;

class Customoptionmanager extends \Magento\Framework\Model\AbstractModel
{
    protected function _construct()
    {
        $this->_init('Vendor\Customoptionmanager\Model\ResourceModel\Customoptionmanager');
    }
}

Block file Code:

<?php

use Vendor\Customoptionmanager\Model\CustomoptionmanagerFactory;
use Magento\Framework\Data\Collection;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class CustomoptionmanagerList extends Template
{
    protected $_modelCustomoptionmanagerFactory;

    public function __construct(Context $context, 
            CustomoptionmanagerFactory $CustomoptionmanagerList, 
            array $data = [])
        {
            $this->_modelCustomoptionmanagerFactory = $CustomoptionmanagerList;
           parent::__construct($context, $data);
        }

   public function getCustomoptionmanagerList()
   {
      $optionCollection = $this->_modelCustomoptionmanagerFactory->create()->getCollection();
       return $optionCollection;
   }
}
?>

Best Answer

You are using HomepageFactory in dependency injection but you have not put it in use anywhere . It seems like you want to inject instance of Vendor\Customoptionmanager\Model\CustomoptionmanagerFactory which should be done using CustomoptionmanagerFactory in dependency injection .

 public function __construct(Context $context, 
            CustomoptionmanagerFactory $CustomoptionmanagerList, 
            array $data = [])
        {
            $this->_modelCustomoptionmanagerFactory = $CustomoptionmanagerList;
           parent::__construct($context, $data);
        }
Related Topic