How to create a Magento2 Admin Grid

May 12, 2013   //   by kdecom   //   magento, magento-extension, magento2, magento2-tutorial  //  No Comments

How to create a Magento2 Admin Grid

What i learn from this extension is…

  • How admin Grid works
  • Admin Layouts.
  • how to add Menu in magento2 admin
  • How to create a magento2 admin grid

Step1:- create a config file

app/code/Kdecom/Blog/eetc/config.xml with the code provided below.

<?xml version="1.0"?>
<config>
    <modules>
        <Kdecom_Blog>
            <version>1.0.0.0</version>
            <active>true</active>
        </Kdecom_Blog>
    </modules>
    <global>
        <resources>
            <blog_setup>
                <setup>
                    <module>Kdecom_Blog</module>
                </setup>
            </blog_setup>
        </resources>
    </global>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <blog before="Mage_Adminhtml">Kdecom_Blog_Adminhtml</blog>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>

    <frontend>
        <routers>
            <blog>
                <use>standard</use>
                <args>
                    <module>Kdecom_Blog</module>
                    <frontName>blog</frontName>
                </args>
            </blog>
        </routers>
        <layout>
            <updates>
                <blog module="Kdecom_Blog">
                    <file>layout.xml</file>
                </blog>
            </updates>
        </layout>
    </frontend>
    <adminhtml>
        <layout>
            <updates>
                <blog module="Kdecom_Blog">
                    <file>layout.xml</file>
                </blog>
            </updates>
        </layout>
    </adminhtml>
</config>

<Kdecom_Blog> <version>1.0.0.0</version> <active>true</active> </Kdecom_Blog>

The above code is just saying your module is enabled. If you set as false it will disable the blog module.

Step2:-

create your sql file:-

/app/code/Kdecom/Blog/sql/blog_setup/install-1.0.0.0.php with this code

 

<?php

$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */

$installer->startSetup();

$blogtable = $installer->getConnection()
    ->newTable($installer->getTable('kd_blog'))
    ->addColumn('post_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
        'identity'  => true,
        'unsigned'  => true,
        'nullable'  => false,
        'primary'   => true,
        ), 'Post Id')
    ->addColumn('post_title', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        ), 'Post Title')
    ->addColumn('post_content', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array(
        ), 'Post Content')
    ->addColumn('post_status', Varien_Db_Ddl_Table::TYPE_TEXT, 25, array(
        ), 'Post Status')
    ->addColumn('created_datetime', Varien_Db_Ddl_Table::TYPE_DATETIME, null, array(
        ), 'Created Time')
    ->addColumn('update_datetime', Varien_Db_Ddl_Table::TYPE_DATETIME, null, array(
        ), 'Updated Time')
    ->addColumn('meta_keywords', Varien_Db_Ddl_Table::TYPE_TEXT, 512, array(
        ), 'Meta Keywords')
    ->addColumn('meta_description', Varien_Db_Ddl_Table::TYPE_TEXT, 512, array(
        ), 'Meta Keywords')
    ->addColumn('meta_title', Varien_Db_Ddl_Table::TYPE_TEXT, 512, array(
        ), 'Meta Keywords');
$installer->getConnection()->createTable($blogtable);

$commenttable = $installer->getConnection()
    ->newTable($installer->getTable('kd_blog_comment'))
    ->addColumn('comment_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
        'identity'  => true,
        'unsigned'  => true,
        'nullable'  => false,
        'primary'   => true,
        ), 'Comment Id')
    ->addColumn('post_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
        ), 'Post Id')
    ->addColumn('comment_content', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array(
        ), 'Comment Content')
    ->addColumn('comment_status', Varien_Db_Ddl_Table::TYPE_TEXT, 25, array(
        ), 'Comment Status')
    ->addColumn('user_name', Varien_Db_Ddl_Table::TYPE_DATETIME, null, array(
        ), 'User Name')
    ->addColumn('user_email', Varien_Db_Ddl_Table::TYPE_DATETIME, null, array(
        ), 'User Email');

$installer->getConnection()->createTable($commenttable);

$installer->endSetup();

Step3:- Now we are going to add a menu in magneto2 admin panel.

Add a file inside the /app/code/Kdecom/Blog/etc/adminhtml/menu.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <menu>
        <add id="Kdecom_Blog::marketing_adminuser_blog" title="Blog" 
             module="Kdecom_Blog" sortOrder="60" parent="Mage_Adminhtml::marketing"  
             resource="Kdecom_Blog::marketing_adminuser_blog"/>
        <add id="Kdecom_Blog::blog_post_list" title="Blogs Grid" module="Kdecom_Blog" sortOrder="40" 
             parent="Kdecom_Blog::marketing_adminuser_blog"
             action="adminhtml/blog_blog/index" resource="Kdecom_Blog::blog_post_list"/>       
    </menu>
</config>

Step4:- Add a controller file inside the

app/code/Kdecom/Blog/controllers/Adminhtml/Blog/BlogController.php

<?php

/**
 *
 * @category   Kdecom
 * @package    KD Manufacturer <www.kdecom.com>
 */
class Kdecom_Blog_Adminhtml_Blog_BlogController extends Mage_Adminhtml_Controller_Action {

    public function indexAction() {
        $this->_title($this->__('Blog Post List'))
                ->_title($this->__('Manage Post'));
        $this->loadLayout();
        $this->renderLayout();
    }
     public function newAction()
    {
        Mage::register('blog_action', 'new');
        $this->_forward('edit');
    }

    public function editAction() {

        $model = Mage::getModel('Kdecom_Blog_Model_Blog');
        $postId = (int) $this->getRequest()->getParam('post_id');
        if ($postId) {
            $model->load($postId);
        }
        $model->setData('update_datetime', date('Y-m-d H:m:s'));

        if ($model->getId()) {
            $data = Mage::getSingleton('Mage_Backend_Model_Session')->getFormData(true);
            if (!empty($data)) {
                $model->setData($data);
            }
        }
        Mage::register('current_blog', $model);

        $this->loadLayout()
                //->_setActiveMenu('system/api')
                ->_title(Mage::helper('Kdecom_Blog_Helper_Data')->__('Post'));

        if (Mage::registry('blog_action') == 'new') {
            $this->_title(Mage::helper('Kdecom_Blog_Helper_Data')->__('Add Post'));
        } else {
            $this->_title(Mage::helper('Kdecom_Blog_Helper_Data')->__('Edit Post'));
        }

        $this->renderLayout();
    }

    public function saveAction() {
        $data = $this->getRequest()->getPost();

        $model = Mage::getModel('Kdecom_Blog_Model_Blog');
        $postId = (int) $this->getRequest()->getParam('post_id');

        if ($postId) {
            $model = $model->load($postId);
        } 
        $model->setUpdateDatetime(date('Y-m-d H:m:s'));
        Mage::register('current_blog', $model);
        if ($data) {
            $model->setData($data);
            if($postId) {
                $model->setId($postId);
            } else {
                $model->setData('created_datetime', date('Y-m-d H:m:s'));
            }
            $model->setData('update_datetime', date('Y-m-d H:m:s'));

            try {
                $model->save();
                $this->_getSession()->addSuccess($this->__("The Post '%s' has been saved.", $model->getPostTitle()));
            } catch (Exception $e) {
                Mage::logException($e);
                $this->_getSession()->addError($e->getMessage());
            }
        } else {
            $this->_getSession()->addError($this->__("The Post '%s' has not been saved.", $model->getPostTitle()));
        }
        $this->_redirect('*/*/');
    }

    public function deleteAction() {
        $model = Mage::getModel('Kdecom_Blog_Model_Blog');

        $postId = (int) $this->getRequest()->getParam('id');
        if ($postId) {
            $model = $model->load($postId);
        }
        if ($model && !$model->getId()) {
            try {
                $model->delete();
                $this->_getSession()->addSuccess($this->__("The Post '%s' has been removed.", $model->getName()));
            }
            catch (Exception $e) {
                Mage::logException($e);
                $this->_getSession()->addError($e->getMessage());
            }
        }
        else {
            $this->_getSession()->addError($this->__("The Post '%s' can not be removed.", $model->getName()));
        }
        $this->_redirect('*/*/');
    }

}

Step5:- Add a Model file at /app/code/Kdecom/Blog/Model/Blog.php with the below code

<?php

class Kdecom_Blog_Model_Blog extends Mage_Core_Model_Abstract {

    public function _construct() {
        parent::_construct();
        $this->_init('Kdecom_Blog_Model_Resource_Blog');
    }
    public function getPostStatusOptions() {
        $status[] = array('label' => 'Please Select','value' => '');
        $status[] = array('label' => 'Draft','value' => 'draft');
        $status[] = array('label' => 'Published','value' => 'published');
        return $status;
    }

}

Next another Model file at  /app/code/Kdecom/Blog/Model/Resource/Blog.php

<?php

class Kdecom_Blog_Model_Resource_Blog extends Mage_Core_Model_Resource_Db_Abstract {

    public function _construct() {
        $this->_init('kd_blog', 'post_id');
    }

}

We need one more model file at :- app/code/Kdecom/Blog/Model/Resource/Blog/Collection.php

<?php

class Kdecom_Blog_Model_Resource_Blog_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {

    public function _construct() {
        parent::_construct();
        $this->_init('Kdecom_Blog_Model_Blog', 'Kdecom_Blog_Model_Resource_Blog');
    }
}

Now we have to create some admin layout files:- app/code/Kdecom/Blog/view/adminhtml/layout.xml

<?xml version="1.0"?>

<layout>
    <adminhtml_blog_blog_index>
        <reference name="content">
            <block type="Kdecom_Blog_Block_Adminhtml_Blog" name="blog.post.list" />
        </reference>
    </adminhtml_blog_blog_index>

    <adminhtml_blog_blog_edit>
        <update handle="editor"/>
        <reference name="content">
            <block type="Kdecom_Blog_Block_Adminhtml_Blog_Edit"  name="blog.post.edit" />
        </reference>
    </adminhtml_blog_blog_edit>

</layout>

We have to create an empty helper file:-  /app/code/Kdecom/Blog/Helper/Data.php

<?php

class Kdecom_Blog_Helper_Data extends Mage_Catalog_Helper_Data {

}

So at last now we have to create 4 another Block files for grid to work…

Create first block file:- /app/code/Kdecom/Blog/Block/Adminhtml/Blog.php

<?php
class Kdecom_Blog_Block_Adminhtml_Blog extends Mage_Backend_Block_Widget_Grid_Container
{
    /**
     * @var string
     */
    protected $_blockGroup = 'Kdecom_Blog';

    /**
     * @var string
     */
    protected $_controller = 'adminhtml_blog';

    /**
     * Internal constructor.
     */
    protected function _construct()
    {
        parent::_construct();

        $this->_headerText      = $this->__('Blog Post');
    }
}

/app/code/Kdecom/Blog/Block/Adminhtml/Blog/Grid.php

<?php

class Kdecom_Blog_Block_Adminhtml_Blog_Grid extends Mage_Backend_Block_Widget_Grid_Extended {

    public function _construct() {
        parent::_construct();
        $this->setId('blogGrid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(true);
    }

    protected function _prepareCollection() {
        $collection = Mage::getModel('Kdecom_Blog_Model_Blog')->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    protected function _prepareColumns() {
        $this->addColumn('post_id', array(
            'header' => $this->__('Post Id'),
            'align' => 'right',
            'width' => '50px',
            'index' => 'post_id',
        ));

        $this->addColumn('post_title', array(
            'header' => $this->__('Title'),
            'align' => 'left',
            'index' => 'post_title',
        ));
        $this->addColumn('update_datetime', array(
            'header' => $this->__('Post Last Updated DateTime'),
            'align' => 'left',
            'index' => 'update_datetime',
        ));

        $this->addColumn('meta_title', array(
            'header' => $this->__('Meta Title'),
            'align' => 'left',
            'index' => 'meta_title',
        ));

        $this->addColumn('action', array(
            'header' => Mage::helper('Kdecom_Blog_Helper_Data')->__('Action'),
            'width' => '100',
            'type' => 'action',
            'getter' => 'getId',
            'actions' => array(
                array(
                    'caption' => Mage::helper('Kdecom_Blog_Helper_Data')->__('Edit'),
                    'url' => array('base' => '*/*/edit'),
                    'field' => 'post_id'
                )
            ),
            'filter' => false,
            'sortable' => false,
            'index' => 'stores',
            'is_system' => true,
        ));

        return parent::_prepareColumns();
    }

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

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

}

Next file app/code/Kdecom/Blog/BlockAdminhtml/Blog/Edit.php

<?php

class Kdecom_Blog_Block_Adminhtml_Blog_Edit extends Mage_Adminhtml_Block_Widget_Form_Container {

    protected function _construct() {
        $this->_objectId = 'id';
        $this->_blockGroup = 'Kdecom_Blog';
        $this->_controller = 'adminhtml_blog';

        parent::_construct();

        $this->getCanLoadTinyMce();
        $this->_updateButton('save', 'label', Mage::helper('Mage_Customer_Helper_Data')->__('Save Post'));
        $this->_updateButton('delete', 'label', Mage::helper('Mage_Customer_Helper_Data')->__('Delete Post'));
    }

}

Last file /app/code/Kdecom/Blog/Block/Adminhtml/Blog/Edit/Form.php

<?php

class Kdecom_Blog_Block_Adminhtml_Blog_Edit_Form extends Mage_Backend_Block_Widget_Form {

    protected function _prepareLayout() {
        parent::_prepareLayout();
        if (Mage::getSingleton('Mage_Cms_Model_Wysiwyg_Config')->isEnabled()) {
            $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
        }
    }

    protected function _prepareForm() {

        $blogPost = Mage::registry('current_blog');
        $form = new Varien_Data_Form(
                        array(
                            'id' => 'edit_form',
                            'action' => $this->getUrl(
                                    '*/*/save', array('post_id' => $blogPost->getId())
                            ),
                            'method' => 'post'
                        )
        );

        $fieldset = $form->addFieldset('blog_fieldset', array('legend' => $this->__('Blog Post')));

        $fieldset->addField(
            'post_title', 'text', array(
            'label' => $this->__('Post Title'),
            'class' => 'required-entry',
            'required' => true,
            'name' => 'post_title',
                )
        );

        $fieldset->addField(
                'post_content', 'editor', array(
            'label' => $this->__('Post Content'),
            'class' => 'required-entry',
            'style' => 'width:725px;height:460px',
            'required' => true,
            'force_load' => true,
            'name' => 'post_content',
            'config' => Mage::getSingleton('Mage_Cms_Model_Wysiwyg_Config')->getConfig($config)
                )
        );

        $postStatus = array();
        $postStatus = Mage::getModel('Kdecom_Blog_Model_Blog')->getPostStatusOptions();
        $fieldset->addField('post_status', 'select', array(
            'label' => $this->__('Post Status'),
            'required' => true,
            'values' => $postStatus,
            'name' => 'post_status',
        ));

        $fieldset->addField('meta_title', 'text', array(
            'label' => $this->__('Meta Title'),
            'required' => false,
            'name' => 'meta_title'
        ));
        $fieldset->addField('meta_keywords', 'textarea', array(
            'label' => $this->__('Meta Keywords'),
            'required' => false,
            'style' => 'width:725px;height:200px',
            'name' => 'meta_keywords',
            'values' => $postStatus,
        ));
        $fieldset->addField('meta_description', 'textarea', array(
            'label' => $this->__('Meta Description'),
            'style' => 'width:725px;height:200px',
            'name' => 'meta_description',
            'required' => false
        ));

        $values = $blogPost->getData();
        $form->setUseContainer(true);
        $form->setValues($values);
        $this->setForm($form);
        return parent::_prepareForm();
    }

}

Now you can try to login into the admin panel and you will be able to see the menu under marketing with Blog. Click on Grid
You will be able to see the Post Grid.
blog-grid-magento2-admin

Leave a comment

css.php