8

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?

1
  • 2
    For Magento 2. I'm using below CRUD generator mage2gen.com
    – Jackson
    Aug 17, 2016 at 3:38

2 Answers 2

27

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

enter image description here

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

<?php
namespace <vendor>\<module>\Model;
use Magento\Framework\Model\AbstractModel;
class Example extends AbstractModel
{
    /**
     * Define resource model
     */
    protected function _construct()
    {
    $this->_init('<vendor>\<module>\Model\ResourceModel\Example');
    }
}

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

<?php
namespace <vendor>\<module>\Model\Resource;
class Example extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    /**
     * Define the main table
     */
    protected function _construct()
    {
    $this->_init('custom_table_name', 'id');   //here id is the primary key of custom table
    }
}

3. Collection

In the collection, you need to define the Model and Resource Model.

app/code/<vendor>/<module>/Model/ResourceModel/Example/Collection.php

<?php
namespace <vendor>\<module>\Model\ResourceModel\Example;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Define model & resource model
     */
    protected function _construct()
    {
    $this->_init(
        '<vendor>\<module>\Model\Example',
        '<vendor>\<module>\Model\ResourceModel\Example'
    );
    
    }
}

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 location

In 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

………………….
………………….

protected $_exampleFactory; 

public function __construct( <vendor>\<module>\Model\ExampleFactory $db)
{
    $this->_exampleFactory = $db;
}
public function anyMethodYouWant()
{
//set value
$this->_exampleFactory->create()->setData(array('event_name' => 'xyz', 'event_imgurl' => 'xyz',...............))->save();

//get value
$data=$this->_exampleFactory->create()->getCollection();
foreach ($data as $d ) 
{
       echo $d->getEventImgurl();   //table field event_imgurl
       echo $d->getEventName();    //table field event_name
}

}

after that, you can call this block method in your template file

<?php $block->anyMethodYouWant(); ?>
4
  • @Bilal - (where I have to write this code I mean pls give path) protected $_exampleFactory; public function __construct( <vendor>/<module>/Model/ExampleFactory $db) { $this->_exampleFactory = $db; } public function anyMethodYouWant() { $this->_exampleFactory->create()->setData(array('event_name' => 'xyz', 'event_imgurl' => 'xyz',...............))->save(); $data=$this->_exampleFactory->create()->getCollection(); foreach ($data as $d ) { echo $d->getEventImgurl(); echo $d->getEventName(); } } Feb 17, 2017 at 6:54
  • Well Explain @BilalUsean . :) May 5, 2017 at 5:38
  • Finally I found a simple and easy explanation for doing models on Magento2
    – Marc Pont
    May 10, 2017 at 13:53
  • Thanks a lot for your answer! Very simple to follow and the explanations about the default existing Factory in Magento 2 is a life saver. Just couldn't find anything clear about it. Have been struggling for months trying to figure out how to work with Magento 2, your answer helps me unblock some points and move forward.
    – Seb
    Oct 7, 2020 at 3:49
0

I don't understand the last piece. Sorry. The last code snippet I have to put in a directory "Block"? And how should I call it? The call block I put is in an HTML file, but I get an error? Please support?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.