Magento – How to get data from custom MySQL table into your Adminhtml grid table

adminhtmlMySQL

I'm using Magento 1.9.0.1!

Right now i am working on a custom magento extension.
I want to display data from a custom MySQL table to my custom page in HTML grid table.

Here is a screen shot of the grid table that i've created in my admin panel:

enter image description here

Here are all files which i've created to achieve this.

In my /app/code/community/VivasIndustries/SmsNotification/etc/config.xml:

<?xml version="1.0"?>
<config>
  <modules>
    <VivasIndustries_SmsNotification>
      <version>0.1.0</version>
    </VivasIndustries_SmsNotification>
  </modules>
  <global>
    <models>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Model</class>
            <resourceModel>vivasindustries_smsnotification_resource</resourceModel>
        </smsnotification>
        <vivasindustries_smsnotification_resource>
        <class>VivasIndustries_SmsNotification_Model_Resource</class>
        <entities>
            <smsnotification>
            <table>VivasIndustries_SmsNotification</table>
            </smsnotification>
        </entities>
        </vivasindustries_smsnotification_resource>
    </models>
    <resources>
        <smsnotification_setup>
            <setup>
                <module>VivasIndustries_SmsNotification</module>
            </setup>
        </smsnotification_setup>
    </resources>    
    <events>
        <sales_order_save_after>
            <observers>
                <vivasindustries_smsnotification>
                    <class>smsnotification/observer</class>
                    <method>orderSaved</method>
                </vivasindustries_smsnotification>
            </observers>
        </sales_order_save_after>
    </events>
    <helpers>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Helper</class>
        </smsnotification>
    </helpers>
    <blocks>
        <smsnotification>
             <class>VivasIndustries_SmsNotification_Block</class>
        </smsnotification>
    </blocks>
  </global>
  <adminhtml>
    <acl>
        <resources>
            <all>
                <title>Allow Everything</title>
            </all>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <vivas>
                                        <title>Vivas - All</title>
                                    </vivas>
                                </children>
                            </config>
                        </children>
                    </system>
                </children>
            </admin>
        </resources>
    </acl>
    </adminhtml>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <VivasIndustries_SmsNotification before="Mage_Adminhtml">VivasIndustries_SmsNotification_Adminhtml</VivasIndustries_SmsNotification>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
</config>   

In my /app/code/community/VivasIndustries/SmsNotification/etc/adminhtml.xml:

<?xml version="1.0"?>
<config>
    <menu>
        <vivassms translate="title" module="smsnotification">
            <title>SMS Center</title>
            <sort_order>110</sort_order>
            <children>

                <settings>
                    <title>Settings</title>
                    <action>adminhtml/system_config/edit/section/vivas/</action>
                    <sort_order>10</sort_order>
                </settings>
                <smsorderstatuses translate="title" module="smsnotification">
                    <title>SMS on Order Statuses</title>
                    <action>adminhtml/smsorderstatuses</action>
                    <sort_order>11</sort_order>
                </smsorderstatuses>
                <about translate="title" module="smsnotification">
                    <title>About</title>
                    <action>adminhtml/about</action>
                    <sort_order>12</sort_order>
                </about>
            </children>
        </vivassms>
    </menu>
    <acl>
        <resources>
            <admin>
                <children>
                    <vivassms>
                        <title>SMS</title>
                        <children>
                            <sendsms translate="title" module="smsnotification">
                                <title>Send SMS</title>
                            </sendsms>
                            <settings>
                                <title>Settings</title>
                                <children>
                                    <smsprofile translate="title" module="smsnotification">
                                        <title>Edit user account</title>
                                    </smsprofile>
                                </children>
                            </settings>
                            <smsorderstatuses translate="title" module="smsnotification">
                                <title>SMS on Order Statuses</title>
                            </smsorderstatuses>
                            <about translate="title" module="smsnotification">
                                <title>About</title>
                            </about>
                        </children>
                    </vivassms>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <vivassms translate="title" module="smsnotification">
                                        <title>Vivas SMS</title>
                                    </vivassms>
                                </children>
                            </config>
                        </children>
                    </system>
                </children>
            </admin>
        </resources>
    </acl>
</config>

In my /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sales/Status.php:

<?php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sales_Status extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        $this->_blockGroup = 'smsnotification';
        $this->_controller = 'adminhtml_sales_status';
        $this->_headerText = Mage::helper('smsnotification')->__('Send SMS on Order Status Changes');

        parent::__construct();
        $this->_removeButton('add');
    }
}

In my /app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sales/Status/Grid.php:

<?php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sales_Status_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('smsnotification_grid');
        $this->setDefaultSort('increment_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }

    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('sales/order_collection')
            ->join(array('a' => 'sales/order_address'), 'main_table.entity_id = a.parent_id AND a.address_type != \'billing\'', array(
                'city'       => 'city',
                'country_id' => 'country_id'
            ))
            ->join(array('c' => 'customer/customer_group'), 'main_table.customer_group_id = c.customer_group_id', array(
                'customer_group_code' => 'customer_group_code'
            ))
            ->addExpressionFieldToSelect(
                'fullname',
                'CONCAT({{customer_firstname}}, \' \', {{customer_lastname}})',
                array('customer_firstname' => 'main_table.customer_firstname', 'customer_lastname' => 'main_table.customer_lastname'))
            ->addExpressionFieldToSelect(
                'products',
                '(SELECT GROUP_CONCAT(\' \', x.name)
                    FROM sales_flat_order_item x
                    WHERE {{entity_id}} = x.order_id
                        AND x.product_type != \'configurable\')',
                array('entity_id' => 'main_table.entity_id')
            )
        ;

        $this->setCollection($collection);
        parent::_prepareCollection();
        return $this;
    }

    protected function _prepareColumns()
    {
        $helper = Mage::helper('smsnotification');
        $currency = (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);

        $this->addColumn('increment_id', array(
            'header' => $helper->__('Order #'),
            'index'  => 'increment_id'
        ));

        $this->addColumn('purchased_on', array(
            'header' => $helper->__('Purchased On'),
            'type'   => 'datetime',
            'index'  => 'created_at'
        ));

        $this->addColumn('products', array(
            'header'       => $helper->__('Products Purchased'),
            'index'        => 'products',
            'filter_index' => '(SELECT GROUP_CONCAT(\' \', x.name) FROM sales_flat_order_item x WHERE main_table.entity_id = x.order_id AND x.product_type != \'configurable\')'
        ));

        $this->addColumn('fullname', array(
            'header'       => $helper->__('Name'),
            'index'        => 'fullname',
            'filter_index' => 'CONCAT(customer_firstname, \' \', customer_lastname)'
        ));

        $this->addColumn('city', array(
            'header' => $helper->__('City'),
            'index'  => 'city'
        ));

        $this->addColumn('country', array(
            'header'   => $helper->__('Country'),
            'index'    => 'country_id',
            'renderer' => 'adminhtml/widget_grid_column_renderer_country'
        ));

        $this->addColumn('customer_group', array(
            'header' => $helper->__('Customer Group'),
            'index'  => 'customer_group_code'
        ));

        $this->addColumn('grand_total', array(
            'header'        => $helper->__('Grand Total'),
            'index'         => 'grand_total',
            'type'          => 'currency',
            'currency_code' => $currency
        ));

        $this->addColumn('shipping_method', array(
            'header' => $helper->__('Shipping Method'),
            'index'  => 'shipping_description'
        ));

        $this->addColumn('order_status', array(
            'header'  => $helper->__('Status'),
            'index'   => 'status',
            'type'    => 'options',
            'options' => Mage::getSingleton('sales/order_config')->getStatuses(),
        ));

        $this->addExportType('*/*/exportInchooCsv', $helper->__('CSV'));
        $this->addExportType('*/*/exportInchooExcel', $helper->__('Excel XML'));

        return parent::_prepareColumns();
    }

    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current'=>true));
    }
}

In my /app/code/community/VivasIndustries/SmsNotification/controllers/Adminhtml/SmsorderstatusesController.php:

<?php

class VivasIndustries_SmsNotification_Adminhtml_SmsorderstatusesController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    {
        $this->_title($this->__('Sales'))->_title($this->__('SMS Center'));
        $this->loadLayout();
        $this->_setActiveMenu('sales/sales');
        $this->_addContent($this->getLayout()->createBlock('smsnotification/adminhtml_sales_status'));
        $this->renderLayout();
    }

    public function gridAction()
    {
        $this->loadLayout();
        $this->getResponse()->setBody(
            $this->getLayout()->createBlock('smsnotification/adminhtml_sales_status_grid')->toHtml()
        );
    }

    public function exportInchooCsvAction()
    {
        $fileName = 'orders_inchoo.csv';
        $grid = $this->getLayout()->createBlock('smsnotification/adminhtml_sales_status_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getCsvFile());
    }

    public function exportInchooExcelAction()
    {
        $fileName = 'orders_inchoo.xml';
        $grid = $this->getLayout()->createBlock('smsnotification/adminhtml_sales_status_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
    }
}

So the deal comes here!!

I want not to show this data like it is described in this guide: http://inchoo.net/magento/how-to-create-a-custom-grid-from-scratch/ but to display the data from my custom table VivasIndustries_SmsNotification.

Let me show you the structure and the data i want to show in the grid table:

enter image description here

So at final, there are two problem which i don't know how to handle!

  1. How i can display this data in the grid table?
  2. How can i create a button to be clicked and then in new opened page you'll be able to place data which will be inserted in VivasIndustries_SmsNotification? I know that there can be a lot of work to be covered question 2 so it is more important to resolve the first one.

Thanks in advance!

Best Answer

The lex.you need to create a model using a custom module.

Step: You have define model class and resource type but not define resource Class

<models>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Model</class> <!-- model prefix class -->
            <resourceModel>vivasindustries_smsnotification_resource</resourceModel>
<!-- model resource type -->

        </smsnotification>
    </models>

So you need to add resource class which is interact the model with database.

  <models>
......
    <vivasindustries_smsnotification_resource>
        <class>VivasIndustries_SmsNotification_Model_Resource</class>
        <entities>
            <custommodule>
            <table>VivasIndustries_SmsNotification</table> <!-- VivasIndustries_SmsNotification is Your db tabale -->
            </custommodule>
        </entities>
        </vivasindustries_smsnotification_resource>
</models>

VivasIndustries_SmsNotification_Model_Resource VivasIndustries_SmsNotification

you need to define class VivasIndustries_SmsNotification_Model_Smsnotification

code is

<?php
class VivasIndustries_SmsNotification_Model_Smsnotification extends extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        $this->_init('smsnotification/smsnotification');
    }

}

Resource class model class:

<?php
class VivasIndustries_SmsNotification_Model_Resource_Smsnotification extends Mage_Core_Model_Resource_Db_Abstract
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('smsnotification/smsnotification','id');
    }
}

Resource Collection model

<?php 
class VivasIndustries_SmsNotification_Model_Resource_Smsnotification_Collection 
extends Mage_Core_Model_Resource_Db_Collection_Abstract{
    protected function _constuct(){
        $this->_init('smsnotification/smsnotification');    
    }
}

[Please study at how create model][1]

Now you get a collection mode.

Now on preapareCollection

you need change code:

$collection =Mage::getResourceModel('smsnotification/smsnotification_collection);

You grid code is:

<?php

class VivasIndustries_SmsNotification_Block_Adminhtml_Smsnotification_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

        public function __construct()
        {
                parent::__construct();
                $this->setId("smsnotificationGrid");
                $this->setDefaultSort("id");
                $this->setDefaultDir("DESC");
                $this->setSaveParametersInSession(true);
        }

        protected function _prepareCollection()
        {
                $collection = Mage::getModel("smsnotification/smsnotification")->getCollection();
                $this->setCollection($collection);
                return parent::_prepareCollection();
        }
        protected function _prepareColumns()
        {
                $this->addColumn("id", array(
                "header" => Mage::helper("smsnotification")->__("ID"),
                "align" =>"right",
                "width" => "50px",
                "type" => "number",
                "index" => "id",
                ));

                $this->addColumn("receiver", array(
                "header" => Mage::helper("smsnotification")->__("Receiver"),
                "index" => "receiver",
                ));
                $this->addColumn("phone", array(
                "header" => Mage::helper("smsnotification")->__("Phome"),
                "index" => "phone",
                ));
                    $this->addColumn('date', array(
                        'header'    => Mage::helper('smsnotification')->__('Data'),
                        'index'     => 'date',
                        'type'      => 'datetime',
                    ));
            $this->addExportType('*/*/exportCsv', Mage::helper('sales')->__('CSV')); 
            $this->addExportType('*/*/exportExcel', Mage::helper('sales')->__('Excel'));

                return parent::_prepareColumns();
        }

        public function getRowUrl($row)
        {
               return $this->getUrl("*/*/edit", array("id" => $row->getId()));
        }



        protected function _prepareMassaction()
        {
            $this->setMassactionIdField('id');
            $this->getMassactionBlock()->setFormFieldName('ids');
            $this->getMassactionBlock()->setUseSelectAll(true);
            $this->getMassactionBlock()->addItem('remove_smsnotification', array(
                     'label'=> Mage::helper('smsnotification')->__('Remove Smsnotification'),
                     'url'  => $this->getUrl('*/adminhtml_smsnotification/massRemove'),
                     'confirm' => Mage::helper('smsnotification')->__('Are you sure?')
                ));
            return $this;
        }


}

Update code at config.xml

<global>
...
<models>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Model</class> <!-- model prefix class -->
            <resourceModel>vivasindustries_smsnotification_resource</resourceModel>
<!-- model resource type -->

        </smsnotification>
    <vivasindustries_smsnotification_resource>
        <class>VivasIndustries_SmsNotification_Model_Resource</class>
        <entities>
            <custommodule>
            <table>VivasIndustries_SmsNotification</table> <!-- VivasIndustries_SmsNotification is Your db tabale -->
            </custommodule>
        </entities>
        </vivasindustries_smsnotification_resource>    
    </models>
    <resources>
      <smsnotification_setup>
        <setup>
          <module>VivasIndustries_SmsNotification</module>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </smsnotification_setup>
      <smsnotification_write>
        <connection>
          <use>core_write</use>
        </connection>
      </smsnotification_write>
      <smsnotification_read>
        <connection>
          <use>core_read</use>
        </connection>
      </smsnotification_read>
    </resources>
.....
</global>


  [1]: http://www.amitbera.com/create-an-magento-extension-with-custom-database-table/
Related Topic