A Basic Brand new module ….

First u should use this type of structure of the directory of files

These file is under app/code/local/Imran……….

Imran
—–/News
———–/Block/News.php
——————/Adminhtml/News.php
—————————–/News/Grid.php & Edit.php
———————————–/Edit/Form.php & Tabs.php
—————————————/Tab/Form.php
———–/Helper/Data.php
———–/Model/News.php
—————–/Mysql4/News.php
————————/News/Collection.php
———–/controllers/IndexController.php
———–/controllers/Adminhtml/NewsController.php
———–/etc/config.xml
———–/sql
————–/news_setup/mysql4-install-0.1

app/etc/modules/Imran_News.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : Imran_News.xml.xml
    Created on : July 26, 2010, 10:14 AM
    Author     : Imran
    Description:
        Purpose of the document follows.
-->
<config>
    <modules>
        <Imran_News>
            <active>true</active>
            <codePool>local</codePool>
        </Imran_News>
    </modules>
</config>

app/code/local/Imran/News/Block/News.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php 
class Imran_News_Block_News extends Mage_Core_Block_Template
{
    public function __construct()
    {
        parent::__construct();
        $this->setTemplate('news/news.phtml');
    }
}

app/code/local/Imran/News/Block/Adminhtml/News.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Block_Adminhtml_News extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        $this->_controller = 'adminhtml_news';
        $this->_blockGroup = 'news';
        $this->_headerText = Mage::helper('news')->__('Item Manager');
        $this->_addButtonLabel = Mage::helper('news')->__('Add Item');
        parent::__construct();
    }
}

app/code/local/Imran/News/Block/Adminhtml/News/Grid.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Block_Adminhtml_News_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('newsGrid');
        // This is the primary key of the database
        $this->setDefaultSort('news_id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(true);
    }

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

    protected function _prepareColumns()
    {
        $this->addColumn('news_id', array(
            'header'    => Mage::helper('news')->__('ID'),
            'align'     =>'right',
            'width'     => '50px',
            'index'     => 'news_id',
        ));

        $this->addColumn('title', array(
            'header'    => Mage::helper('news')->__('Title'),
            'align'     =>'left',
            'index'     => 'title',
        ));

        /**/
        $this->addColumn('content', array(
            'header'    => Mage::helper('news')->__('Item Content'),
            'width'     => '150px',
            'index'     => 'content',
        ));
        

        $this->addColumn('created_time', array(
            'header'    => Mage::helper('news')->__('Creation Time'),
            'align'     => 'left',
            'width'     => '120px',
            'type'      => 'date',
            'default'   => '--',
            'index'     => 'created_time',
        ));

        $this->addColumn('update_time', array(
            'header'    => Mage::helper('news')->__('Update Time'),
            'align'     => 'left',
            'width'     => '120px',
            'type'      => 'date',
            'default'   => '--',
            'index'     => 'update_time',
        ));


        $this->addColumn('status', array(

            'header'    => Mage::helper('news')->__('Status'),
            'align'     => 'left',
            'width'     => '80px',
            'index'     => 'status',
            'type'      => 'options',
            'options'   => array(
                1 => 'Active',
                0 => 'Inactive',
            ),
        ));

//add a new field in database and it show in grid mode in magento admin panel ....
         $this->addColumn('remarks', array(
            'header'    => Mage::helper('news')->__('Remarks'),
            'align'     =>'left',
            'index'     => 'remarks',
        ));

        return parent::_prepareColumns();
    }

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


}

app/code/local/Imran/News/Block/Adminhtml/News/Edit.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Block_Adminhtml_News_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();

        $this->_objectId = 'id';
        $this->_blockGroup = 'news';
        $this->_controller = 'adminhtml_news';

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

    public function getHeaderText()
    {
        if( Mage::registry('news_data') && Mage::registry('news_data')->getId() ) {
            return Mage::helper('news')->__("Edit Item '%s'", $this->htmlEscape(Mage::registry('news_data')->getTitle()));
        } else {
            return Mage::helper('news')->__('Add Item');
        }
    }
}

app/code/local/Imran/News/Block/Adminhtml/News/Edit/Tabs.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Block_Adminhtml_News_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{

    public function __construct()
    {
        parent::__construct();
        $this->setId('news_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle(Mage::helper('news')->__('News Information'));
    }

    protected function _beforeToHtml()
    {
        $this->addTab('form_section', array(
            'label'     => Mage::helper('news')->__('Item Information'),
            'title'     => Mage::helper('news')->__('Item Information'),
            'content'   => $this->getLayout()->createBlock('news/adminhtml_news_edit_tab_form')->toHtml(),
        ));

        return parent::_beforeToHtml();
    }
}

app/code/local/Imran/News/Block/Adminhtml/News/Edit/Form.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Block_Adminhtml_News_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(array(
                                        'id' => 'edit_form',
                                        'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
                                        'method' => 'post',
                                     )
        );

        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
}

app/code/local/Imran/News/Block/Adminhtml/News/Edit/Tab/Form.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Block_Adminhtml_News_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
 
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $this->setForm($form);
        $fieldset = $form->addFieldset('news_form', array('legend'=>Mage::helper('news')->__('Item information')));

        $fieldset->addField('title', 'text', array(
            'label'     => Mage::helper('news')->__('Title'),
            'class'     => 'required-entry',
            'required'  => true,
            'name'      => 'title',
        ));

        $fieldset->addField('status', 'select', array(
            'label'     => Mage::helper('news')->__('Status'),
            'name'      => 'status',
            'values'    => array(
                array(
                    'value'     => 1,
                    'label'     => Mage::helper('news')->__('Active'),
                ),

                array(
                    'value'     => 0,
                    'label'     => Mage::helper('news')->__('Inactive'),
                ),
            ),
        ));

        $fieldset->addField('content', 'editor', array(
            'name'      => 'content',
            'label'     => Mage::helper('news')->__('Content'),
            'title'     => Mage::helper('news')->__('Content'),
            'style'     => 'width:98%; height:400px;',
            'wysiwyg'   => true,
            'required'  => true,
        ));
 // add created time in database
       /* $outputFormat = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM);
            $fieldset->addField('created_time', 'date', array(
            'name' => 'created_time',
            'label' => Mage::helper('news')->__('Created Time'),
            'image' => $this->getSkinUrl('images/grid-cal.gif'),
            'format' => $outputFormat,
            'time' => true,
            'style' => 'width: 140px;'
        ));
*/
        $outputFormat = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM);
        // if($queue->getQueueStatus() == Mage_Newsletter_Model_Queue::STATUS_NEVER) {
            $fieldset->addField('created_time', 'date',array(
              'name'      =>    'created_time',
              'time'      =>    true,
              'format'    =>    $outputFormat,
              'label'     =>    Mage::helper('news')->__('Created Time'),
              'image'     =>    $this->getSkinUrl('images/grid-cal.gif')
            ));
// add a new field in database to show in adding in database in put format in admin panel...
         $fieldset->addField('remarks', 'text', array(
            'label'     => Mage::helper('news')->__('Remarks'),
           // 'class'     => 'required-entry',
            'required'  => false,
            'name'      => 'remarks',
        ));
//print(Mage::getSingleton('adminhtml/session')->getNewsData());
        if ( Mage::getSingleton('adminhtml/session')->getNewsData() )
        {
            $form->setValues(Mage::getSingleton('adminhtml/session')->getNewsData());
          //  print_r($varab);
            Mage::getSingleton('adminhtml/session')->setNewsData(null);
        } elseif ( Mage::registry('news_data') ) {
            $form->setValues(Mage::registry('news_data')->getData());
        }
        return parent::_prepareForm();
    }
}

app/code/local/Imran/News/Helper/Data.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Helper_Data extends Mage_Core_Helper_Abstract
{

}

app/code/local/Imran/News/Model/News.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * 	class Fend_Feed_Model_Feed extends Mage_Core_Model_Abstract
	{
		public function _construct() {
			parent::_construct();
			$this->_init('feed/feed');
		}
	} 
 */

?>
<?php

class Imran_News_Model_News extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('news/news');
    }
}

app/code/local/Imran/News/Model/Mysql4/News.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Model_Mysql4_News extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {
        $this->_init('news/news', 'news_id');
    }
}

app/code/local/Imran/News/Model/Mysql4/News/Collection.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php

class Imran_News_Model_Mysql4_News_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
    public function _construct()
    {
        //parent::__construct();
        $this->_init('news/news');
    }
}

app/code/local/Imran/News/controllers/IndexController.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.

 * <?php

class Fend_Feed_IndexController extends Mage_Core_Controller_Front_Action
{
	public function indexAction() {
		$this->loadLayout();
		$this->renderLayout();
	}
}

?>
 *  */

?>
<?php
class Imran_News_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
            $this->loadLayout();
            $this->renderLayout();
    }
}

app/code/local/Imran/News/controllers/Adminhtml/NewsController.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * public function indexAction() {
  $this->_initAction()
    ->renderLayout();
}
 * to
 * public function indexAction() {
  $this->_initAction();
  $this->_addContent($this->getLayout()->createBlock('module/adminhtml_module_grid'));
  $this->renderLayout();
}
 *
 */

?>
<?php
 
class Imran_News_Adminhtml_NewsController extends Mage_Adminhtml_Controller_action
{

    protected function _initAction()
    {
        $this->loadLayout()
            ->_setActiveMenu('news/items')
            ->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
        return $this;
    }

    public function indexAction() {
        $this->_initAction();
        //$this->_addContent($this->getLayout()->createBlock('news/adminhtml_news_grid'));
        $this->renderLayout();
    }

    public function editAction()
    {
        $newsId     = $this->getRequest()->getParam('id');
        $newsModel  = Mage::getModel('news/news')->load($newsId);

        if ($newsModel->getId() || $newsId == 0) {

            Mage::register('news_data', $newsModel);

            $this->loadLayout();
            $this->_setActiveMenu('news/items');

            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));

            $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

            $this->_addContent($this->getLayout()->createBlock('news/adminhtml_news_edit'))
                 ->_addLeft($this->getLayout()->createBlock('news/adminhtml_news_edit_tabs'));

            $this->renderLayout();
        } else {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('news')->__('Item does not exist'));
            $this->_redirect('*/*/');
        }
    }

    public function newAction()
    {
        $this->_forward('edit');
    }

    public function saveAction()
    {
        if ( $this->getRequest()->getPost() ) {
            try {
                $postData = $this->getRequest()->getPost();
                $newsModel = Mage::getModel('news/news');
                $newsModel->setId($this->getRequest()->getParam('id'))
                    ->setTitle($postData['title'])
                    ->setContent($postData['content'])
                    ->setStatus($postData['status'])
                    ->setRemarks($postData['remarks'])
                    ->setcreated_time($postData['created_time'])
                    ->save();

                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully saved'));
                Mage::getSingleton('adminhtml/session')->setNewsData(false);

                $this->_redirect('*/*/');
                return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setNewsData($this->getRequest()->getPost());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        $this->_redirect('*/*/');
    }

    public function deleteAction()
    {
        if( $this->getRequest()->getParam('id') > 0 ) {
            try {
                $newsModel = Mage::getModel('news/news');

                $newsModel->setId($this->getRequest()->getParam('id'))
                    ->delete();

                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
                $this->_redirect('*/*/');
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            }
        }
        $this->_redirect('*/*/');
    }
}

app/code/local/Imran/News/etc/config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : config.xml
    Created on : July 26, 2010, 10:19 AM
    Author     : Imran
    Description:
        Purpose of the document follows.
-->

<config>
    <modules>
        <Imran_News>
            <version>0.1.0</version>
        </Imran_News>
    </modules>
    <frontend>
        <routers>
            <news>
                <use>standard</use>
                <args>
                    <module>Imran_News</module>
                    <frontName>news</frontName>
                </args>
            </news>
        </routers>
        <layout>
            <updates>
                <news>
                    <file>news.xml</file>
                </news>
            </updates>
        </layout>
    </frontend>
    <admin>
        <routers>
            <news>
                <use>admin</use>
                <args>
                    <module>Imran_News</module>
                    <frontName>news</frontName>
                </args>
            </news>
        </routers>
    </admin>
    <adminhtml>
        <menu>
            <news module="news">
                <title>News</title>
                <sort_order>71</sort_order>
                <children>
                    <items module="news">
                        <title>Manage Items</title>
                        <sort_order>0</sort_order>
                        <action>news/adminhtml_news</action>
                    </items>
                </children>
            </news>
        </menu>
        <acl>
            <resources>
                <all>
                    <title>Allow Everything</title>
                </all>
                <admin>
                    <children>
                        <news>
                            <title>News Module</title>
                            <sort_order>200</sort_order>
                        </news>
                    </children>
                </admin>
            </resources>
        </acl>
        <layout>
            <updates>
                <news>
                    <file>news.xml</file>
                </news>
            </updates>
        </layout>
    </adminhtml>
    <global>
        <models>
            <news>
                <class>Imran_News_Model</class>
                <resourceModel>news_mysql4</resourceModel>
            </news>
            <news_mysql4>
                <class>Imran_News_Model_Mysql4</class>
                <entities>
                    <news>
                        <table>news</table>
                    </news>
                </entities>
            </news_mysql4>
        </models>
        <resources>
            <news_setup>
                <setup>
                    <module>Imran_News</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </news_setup>
            <news_write>
                <connection>
                    <use>core_write</use>
                </connection>


            </news_write>
            <news_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </news_read>
        </resources>
        <blocks>
            <news>
                <class>Imran_News_Block</class>
            </news>
        </blocks>
        <helpers>
            <news>
                <class>Imran_News_Helper</class>
            </news>
        </helpers>
    </global>
</config>

app/code/local/Imran/News/sql/news_setup/mysql4-install-0.1.php

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

?>
<?php
 
$installer = $this;

$installer->startSetup();

$installer->run("

-- DROP TABLE IF EXISTS {$this->getTable('news')};
CREATE TABLE {$this->getTable('news')} (
  `news_id` int(11) unsigned NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `content` text NOT NULL default '',
  `status` smallint(6) NOT NULL default '0',
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`news_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    ");

$installer->endSetup();

The above code is used as a core in formation ……

app/design/your theme/template/news/news.phtml

<h4><?php echo $this->__('Module List') ?></h4>

<?php
        /*
        This will load one record from your database table.
        load(<module>_id) will load whatever ID number you give it.
        */
    /**/
    $news = Mage::getModel('news/news')->load(1);
    echo $news->getNewsId();
    echo $news->getTitle();
    echo $news->getContent();
    echo $news->getStatus();
    

        /*
        This block of code loads all of the records in the database table.
        It will iterate through the collection and the first thing it will do
        is set the Title to the current value of $i which is incremented each
        iteration and then echo that value back out.  At the very end it will
        save the entire collection.
        */
    /**/
    $i = 0;

    $collection = Mage::getModel('news/news')->getCollection();
   // print_r($collection);
    $collection->setPageSize(5);
    $collection->setCurPage(2);
    $size = $collection->getSize();
    $cnt = count($collection);
    foreach ($collection as $item) {
        $i = $i+1;
        $item->setTitle($i);
        echo $item->getTitle();echo '<br/>';
    }

    $collection->walk('save');
    

        /*
        This shows how to load one value, change something and save it.
        */

    /**/
    $object = Mage::getModel('news/news')->load(1);
    $object->setTitle('This is a changed title');
    $object->save();
    
?>

app/design/frontend/your theme/layout/news.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : news.xml
    Created on : July 26, 2010, 10:45 AM
    Author     : Imran
    Description:
        Purpose of the document follows.
-->

<layout version="0.1.0">
    <news_index_index>
        <reference name="content">
            <block type="core/template" name="news" template="news/news.phtml" />
        </reference>
    </news_index_index>
</layout>

app/design/adminhtml/your theme/layout/news.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : news.xml
    Created on : July 26, 2010, 12:17 PM
    Author     : Imran
    Description:
        Purpose of the document follows.
-->

<layout version="0.1.0">
    <news_adminhtml_news_index>
        <reference name="content">
            <block type="news/adminhtml_news" name="news" />
        </reference>
    </news_adminhtml_news_index>
</layout>

Here it is the most basic of a new module that handle any database. Here I use this code with the help of magento wiki help. And first add a table manually from u r phpmyadmin.

Tagged: , , ,

3 thoughts on “A Basic Brand new module ….

  1. MD Saddam November 8, 2010 at 2:07 pm

    this tutorial is help full for me. thanks

  2. Anees Akhter December 23, 2010 at 6:45 pm

    Hi,
    when i did click News AddButton. than not show Add Form show lot of error. but listing show correct. please help me.

  3. lomsimmerne May 5, 2012 at 7:39 pm

    Honeyed Habitation 3D is fabulous. The interface is intuitive and the developers are entirely thoughtful and bonny responsive. This software is uncommonly fair clik here

Comments are closed.