Magento2

How to get the collection of a custom module in Magento 2?

How to get the collection of a custom module in Magento 2?

If you are working on a custom Module in Magento 2 and need to get collections of records from custom database table below are the steps and file list you need to create.

Here created one Custom table for clear understanding using declarative schema.

First of all, create db_schema.xml file and write the following code :

File Path : app/code/V4U/CustomCollections/etc/db_schema.xml

Now, Need to create main three files for getting collection from custom module.

  1. Model, 2. ResourceModel and 3. Collection
  1. Create Model File :

File Path : app/code/V4U/CustomCollections/Model/CustomCollections.php

2. Create ResourceModel File :

File Path : app/code/V4U/CustomCollections/Model/ResourceModel/CustomCollections.php

3. Create Collection File :

File Path : app/code/V4U/CustomCollections/Model/ResourceModel/CustomCollections/Collection.php

How to get custom collections using block file?

Create block file on below file path.

File Path : app/code/V4U/CustomCollections/Block/CustomCollection.php

Create phtml file on below path :

File Path : app/code/V4U/CustomCollections/view/frontend/templates/custom_collections.phtml

How to get custom collections using Dependency Injection?

Need to inject the model collection factory into constructor.

Now you can use in any one of the class methods :

How to get custom collections using ObjectManager?  (It’s not good practice to use directly use ObjectManager. Always use constructor via DI(Dependency injection). Here is just used for concept)

🙂 Happy Coding. Keep Liking & Sharing 💻

Tagged ,