Magento – Magento 2 – Admin module – how to SELECT data from database to display in Admin page

adminadminhtmldatabaseevent-observermagento2

I'm building out an Admin module that's intended to SELECT data from a specific table in magento database and display that data on page, it's a custom table called "commission_sales". At this point I just want to SELECT * (all data) from table and display on page.

The following code does work, i've tested on the order success page and data does pull through. I just can't seem to do the same for the admin page:

Note: I've also tried to trigger this code in events.xml with no luck

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 *  
 */
namespace MyCompany\ExampleAdminNewPage\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;


class commission_data implements ObserverInterface
{
    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $tableName = $resource->getTableName('commission_sales');

        $sql = "SELECT * FROM " . $tableName;
        $result = $connection->fetchAll($sql); 
        echo '<pre> Data currently saved to commission_sales table</pre><pre>'; echo ($result); echo '</pre>';      
    }
}  
?>

How would you incorporate the above SELECT request and then display that data in an admin page/module?

Current files for the admin module so far:

   MyCompany
    `-- ExampleAdminNewPage
        |
        |-- Controller
        |   |-- Adminhtml
        |       |-- HelloWorld
        |           `-- Index.php
        |-- etc
        |   |-- adminhtml
        |   |   |-- menu.xml
        |   |   `-- routes.xml
        |   |   `-- events.xml
        |   `-- module.xml
        |-- view
        |   |-- adminhtml
        |       |-- layout
        |       |    `-- exampleadminnewpage_helloworld_index.xml
        |       `-- templates
        |           `-- helloworld.phtml
        |-- composer.json
        `-- registration.php

Appreciate any help!

Thanks,
Chris

Best Answer

I believe that you are using observer for any admin event. You can add below code in your observer to check that your observer file is being called or not.

public function execute(\Magento\Framework\Event\Observer $observer)
{
  $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
  $logger = new \Zend\Log\Logger();
  $logger->addWriter($writer);
  $logger->info(print_r($result,1));   
}

It will create new log file named 'test.log' and with fetched data print in it.

Related Topic