Magento 2 – How to Get Collection of Custom Module

magento2

I have created a custom module: Vendor_Faq

My module structure is:

Vendor
└───Faq
    │   registration.php
    │
    ├───etc
    │       module.xml
    │
    ├───Model
    │   │   Custom.php

    │   │
    │   └───ResourceModel
    │       │   Custom.php
    │       │
    │       └───Custom
    │               Collection.php
    │
    ├───Setup
    │       InstallSchema.php
    │       
    │
    └───view
        └───frontend
            │___Template
            │       Faq
                        Index.php
            ├───layout
            │       faq_faq_index.xml
            │
        

After the creation of the module, I have written the below code but it's not working.

Below is code with a folder structure:

/block/Faq/Index.php

<?php

namespace Vendor\Faq\Block\Faq;
use Vendor\Faq\Block\BaseBlock;

class Index extends BaseBlock
{
    //public $hello='Hello World';

    protected $mymodulemodelFactory;
    public function __construct(
    \Vendor\Faq\Model\ResourceModel\Custom\CollectionFactory $mymodulemodelFactory, 
    )
    {
        $this->mymodulemodelFactory = $mymodulemodelFactory;
    }
    public function getCollection()
    {
        $collection = $this->mymodulemodelFactory->create();
        return $collection;
    }


}

AND

get collection data folder structure:

/View/Frontend/Template Faq.Index.php

echo $block->getCollection();

but it's not working. After running the code it displays the blank page.

Please suggest a solution?

Best Answer

You can get data using foreach of your collection,

class Index extends BaseBlock
{
    //public $hello='Hello World';

     protected $mymodulemodelFactory;
     public function __construct(
       \Ashore\Faq\Block\Context $context,
       \Ashore\Faq\Model\CustomFactory $mymodulemodelFactory
     )
     {
        $this->mymodulemodelFactory = $mymodulemodelFactory;
        parent::__construct($context);
     }
    public function getCollection()
    {
        $collection = $this->mymodulemodelFactory->create()->getCollection()->addAttributeToSelect('*');
        return $collection;
    }
}

in Block file,

$collection = $block->getCollection();
foreach($collection as $moduledata){
    echo "<pre>";print_r($moduledata->getData());
}

Remove var folder and check.