I have a custom table in my Magento2 database and can not find a simple working example of how to connect, retrieve, and display the field data in a Magento2 page.
This one mostly works but is incomplete because it stops at fetching the field but doesn't show how to actually display the field on the webpage:
http://webkul.com/blog/magento2-write-custom-mysql-query-without-using-model/
Can someone please provide a complete example?
Best Answer
You have mentioned a tutorial that explains CRUD operation without a model, but it is not good practice using object manager.
let me explain the crud operation with the model, it is very simple. This is a very important concept in Magento.
For example, Let's consider the below table structure
For CRUD operation you need to create three things
1. Model
In Model, you need to initialize the resource model
app/code/<vendor>/<module>/Model/Example.php
2. Resource Model
In the Resource model, you need to initialize the table name and primary key.
app/code/<vendor>/<module>/Model/ResourceModel/Example.php
3. Collection
In the collection, you need to define the Model and Resource Model.
app/code/<vendor>/<module>/Model/ResourceModel/Example/Collection.php
That's it, now you can able to fetch table values in any block using dependency injection.
For eg: Get and Set Data in Block
Kindly note, we pass
<module>\<vendor>\Model\ExampleFactory
in the constructor, but none of the files will be found in that locationIn Magento 2, each CRUD model has a corresponding factory class. All factory class names are the name of the model class appended with the word “Factory”.Since our model class is named
<module>/<vendor>/Model/Example
this means our factory class is named<module>/<vendor>/Model/ExampleFactory
after that, you can call this block method in your template file