2

I have created a new table 'custom_table' i need to render the values in a custom template. How to get the values of that table ?

2
  • you have to configure the resource model, please look at this: mageplaza.com/magento-2-module-development/… then you load a collection to get the data, after that you display them in your phtml
    – PЯINCƎ
    Jul 26, 2018 at 14:35
  • How did you see the result? Because I just followed the same procedure but I couldn't able to see any output.
    – Siva
    Jan 31, 2019 at 7:31

1 Answer 1

2

Render the values from custom table in a custom template, Follow bellow steps.

Create Model and ResourceModel in your custom module for collection to get the table's data.

/Your_Magento/app/code/Test/Welcome/Model/Welcome.php

<?php
namespace Test\Welcome\Model;

class Welcome extends \Magento\Framework\Model\AbstractModel
{
    public function _construct()
    {
        $this->_init('Test\Welcome\Model\ResourceModel\Welcome');
    }
}

/Your_Magento/app/code/Test/Welcome/Model/ResourceModel/Welcome.php

<?php
namespace Test\Welcome\Model\ResourceModel;

class Welcome extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    public function _construct()
    {
        $this->_init('test_welcome_welcome', 'id');
    }
}

/Your_Magento/app/code/Test/Welcome/Model/ResourceModel/Welcome/Collection.php

<?php
namespace Test\Welcome\Model\ResourceModel\Welcome;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection 
{
    protected function _construct()
    {
        $this->_init('Test\Welcome\Model\Welcome','Test\Welcome\Model\ResourceModel\Welcome');
    }
}

/Your_Magento/app/code/Test/Welcome/view/frontend/templates/view.phtml

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $model=$objectManager->create('Test\Welcome\Model\Welcome');
    $datacollection=$model->getCollection();

    echo "<table border=1><tr align=center><th>Id</th><th>Fist Name</th><th>Last Name</th></tr>";
    foreach ($datacollection as $data) {
        echo "<tr align=center>";
            echo "<td>".$data->getId()."</td>";
            echo "<td>".$data->getFirstname()."</td>";
            echo "<td>".$data->getLastname()."</td>";
        echo "</tr>";
    }
    echo "</table>";
?>

You can also get data from block using factory method, Calling block from phtml $datacollection = $block->getCollection();

I hope this will useful for you.:)

2
  • This method is working perfectly. But how do we filter result by ID? i tried $datacollection = $model->getCollection->addFieldToFilter('id', $my_id), but it didn't work. Sep 11, 2018 at 15:05
  • 3
    ObjectManager is not recommended. Mar 23, 2019 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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