If you want to use your custom data, you’ll want to generate a custom collection. StackOverflow is flooded (ha! Pun-intended) with answers advising you to use the object manager, but as a wise man once told me:
“using the object manager’s baaad, mkay?”
— Mr. Mackey
The right way to generate a collection from your custom data in your Magento 2 module is using a Factory.
Generate a Custom Collection from a Database Table using a Factory in Magento 2
To gain access to your custom data, you have to define your data as a collection. Tell Magento 2 where your Data-model and its corresponding ResourceModel are:
DaanvdB/ProductQty/Model/ResourceModel/Data/Collection.php
<?php | |
namespace DaanvdB\ProductQty\Model\ResourceModel\Data; | |
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; | |
class Collection extends AbstractCollection { | |
public function _construct() { | |
$this->_init( "DaanvdB\ProductQty\Model\Data", "DaanvdB\ProductQty\Model\ResourceModel\Data" ); | |
} | |
} |
If we want to show the data in a Block, Magento 2 allows us to use our Custom Collection to get the data from our Custom Database Table:
DaanvdB/ProductQty/Block/Data.php
<?php | |
namespace DaanvdB\ProductQty\Block; | |
use Magento\Framework\View\Element\Template; | |
use DaanvdB\ProductQty\Model\DataFactory; | |
class Data extends Template { | |
protected $dataFactory; | |
public function __construct( | |
Template\Context $context, | |
DataFactory $dataFactory | |
) { | |
$this->dataFactory = $dataFactory; | |
parent::__construct( | |
$context | |
); | |
} | |
public function showData() { | |
$collection = $this->dataFactory->create()->getCollection(); | |
$data = $collection->getData(); | |
return $data; | |
} | |
} |
These are the fundamentals for creating a Magento 2 module which allows you to create a custom database table, write data to it and create a custom collection using a factory — and NOT the ObjectManager. I hope it was useful to you. If you have any remarks or questions or just want to compliment me, leave a comment!