Document Conventions
I am going to use a few common conventions here that should make it easier to figure out what you need to replace as I am making this as generic as possible.
Anything in angled brackets (including the angled brackets): , needs to replaced with the appropriate text..
Anything in square brackets (including the square brackets): [ ], needs to replaced with the appropriate text.
The reason I am using two different conventions here are that XML files already use angled brackets so you will only see the square brackets in use in XML files.
NOTE: All directory, file, class names are Case Sensitive unless otherwise noted.
Create Directories
Magento Modules follow a common naming scheme, Namespace_Module. This is very important to remember as you need to be careful about how you name your classes. Every custom module will be created in the directory:
/app/code/local
The first step in creating your custom module is determining the namespace and module name. The namespace is simply an extra division that you can create you module in. This means that you can have two modules named the same thing if they are in two different namespaces. One way to use namespaces is to use your company name or initials for all of your modules. If my company name is Acme and I am creating a module called News the full module name would be Acme_News. Magento uses the namespace Mage. There is nothing stopping you from using that namespace under local, i.e. you could create Mage_News and that would work just fine.
Note : You can not use underscore within your module name
Note2: It seems that currently, if you use upper case characters in module names (expecting to show word starts since neither – nor _ is allowed)… the install will fail or rather the module will not work. Suggestion: use a single upper case character, at the beginning of the name.
Let’s setup our directory structure:
/app/code/local///
Block/
controllers/
etc/
Model/
Mysql4/
/
sql/
_setup/
/app/design/frontend///
template/
/
Activate Module
Magento requires there to be an XML file that tells Magento to look for and use your custom module.
/app/etc/modules/_.xml
true
local
Also you can disable your module in the Configuration menu on the backend via the Advanced tab.
NOTE: Due to a bug in Magento, whitespace is not treated correctly. This means that if you leave space in the values between node names (anything in angled brackets is a node), Magento will break.
As an explanation of the above code you will see that all you are changing is the [Namespace]_[Module] text and leaving everything else the same. Please note the capital P in codePool. If this is lowercase this module will not be active.
Create Controller
/app/code/local///controllers/IndexController.php
<?php
class __IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
}
NOTE: You may notice that there is no closing, ?>, PHP tag in the code. This is a common coding style that Magento core classes use. Magento Coding Standard is similar (with some exceptions) to Zend Framework PHP Coding Standard and you can find the detailed explanations of this rule in Zend Framework Documentation
Create Configuration XML
/app/code/local///etc/config.xml
0.1.0
standard
[Namespace]_[Module]
[module]
[module].xml
[Namespace]_[Module]_Model
[module]_mysql4
[Namespace]_[Module]_Model_Mysql4
[module]
[Namespace]_[Module]
core_setup
core_write
core_read
[Namespace]_[Module]_Block
[Namespace]_[Module]_Helper
NB : You can use the frontName of your choice without any link to your module name. IE : Mage_Catalog could have “mycatalog” as a frontName.
Create Helper
/app/code/local///Helper/Data.php
<?php
class __Helper_Data extends Mage_Core_Helper_Abstract
{
}
Create Models
If you are quite new to Magento you should pay attention to one of its specifics! The Constructors below are not the usual PHP-Constructors!! Keeping that in mind can save hours of frustrating crashes
/app/code/local///Model/.php
<?php
class __Model_ extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init(‘/’);
}
}
/app/code/local///Model/Mysql4/.php
<?php
class __Model_Mysql4_ extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init(‘/’, ‘_id’);
}
}
NOTE: The ‘_id’ refers to the PRIMARY KEY in your database table.
/app/code/local///Model/Mysql4//Collection.php
<?php
class __Model_Mysql4__Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
public function _construct()
{
//parent::__construct();
$this->_init(‘/’);
}
}
SQL Setup
/app/code/local///sql/_setup/mysql4-install-0.1.0.php
startSetup();
$installer->run(”
— DROP TABLE IF EXISTS {$this->getTable(”)};
CREATE TABLE {$this->getTable(”)} (
`_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 (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
“);
$installer->endSetup();
NOTE: Please note the text that needs to be replaced. This SQL structure is up to you, this is merely a starting point.
Note Important: If you add fields and couldn’t save data in these fields please try to go to System→Cache Management Then 1.Flush Cache Storage 2.Flush Magento Cache.
Template Design
/app/design/frontend///layout/.xml
NOTE: The block type will automatically figure out what template file to use based on the second [module] declaration.
As an alternate way of declaring what template file to use you can use this: /app/design/frontend///layout/.xml
/app/design/frontend///template//.phtml
/*
This will load one record from your database table.
load(_id) will load whatever ID number you give it.
*/
/*
$news = Mage::getModel(‘/’)->load(1);
echo $news->getId();
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(‘/’)->getCollection();
$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();
}
$collection->walk(‘save’);
*/
/*
This shows how to load one value, change something and save it.
*/
/*
$object = Mage::getModel(‘/’)->load(1);
$object->setTitle(‘This is a changed title’);
$object->save();
*/
?>
NOTE: Uncomment anything that you would like to use and this is just a starting point and some common methods for you to try and pull the data out.
In this section I am utilizing the built-in Grid Widgets and form capabilities to create a form to allow editing and creating new items for your custom database.
Directory Additions
Here is the revised directory setup due to the additions and changes we need for the backend module.
/app/code/local///
Block/
Adminhtml/
/
Edit/
Tab/
controllers/
Adminhtml/
etc/
Helper/
Model/
Mysql4/
/
sql/
_setup/
Blocks
These control the setup and appearance of your grids and the options that they display.
NOTE: Please note the fact that Block comes before Adminhtml in the class declaration. In any of the Magento modules in Adminhtml it is the opposite. For your module to work it has to be Block_Adminhtml otherwise you will get a ‘Cannot redeclare module…’ error.
/app/code/local///Block/Adminhtml/.php
<?php
class __Block_Adminhtml_ extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = ‘adminhtml_’;
$this->_blockGroup = ”;
$this->_headerText = Mage::helper(”)->__(‘Item Manager’);
$this->_addButtonLabel = Mage::helper(”)->__(‘Add Item’);
parent::__construct();
}
}
/app/code/local///Block/Adminhtml//Edit.php
<?php
class __Block_Adminhtml__Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = ‘id’;
$this->_blockGroup = ”;
$this->_controller = ‘adminhtml_’;
$this->_updateButton(‘save’, ‘label’, Mage::helper(”)->__(‘Save Item’));
$this->_updateButton(‘delete’, ‘label’, Mage::helper(”)->__(‘Delete Item’));
}
public function getHeaderText()
{
if( Mage::registry(‘_data’) && Mage::registry(‘_data’)->getId() ) {
return Mage::helper(”)->__(“Edit Item ‘%s’”, $this->htmlEscape(Mage::registry(‘_data’)->getTitle()));
} else {
return Mage::helper(”)->__(‘Add Item’);
}
}
}
/app/code/local///Block/Adminhtml//Grid.php
<?php
class __Block_Adminhtml__Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId(‘Grid’);
// This is the primary key of the database
$this->setDefaultSort(‘_id’);
$this->setDefaultDir(‘ASC’);
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
protected function _prepareCollection()
{
$collection = Mage::getModel(‘/’)->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn(‘_id’, array(
‘header’ => Mage::helper(”)->__(‘ID’),
‘align’ =>’right’,
‘width’ => ’50px’,
‘index’ => ‘_id’,
));
$this->addColumn(‘title’, array(
‘header’ => Mage::helper(”)->__(‘Title’),
‘align’ =>’left’,
‘index’ => ‘title’,
));
/*
$this->addColumn(‘content’, array(
‘header’ => Mage::helper(”)->__(‘Item Content’),
‘width’ => ’150px’,
‘index’ => ‘content’,
));
*/
$this->addColumn(‘created_time’, array(
‘header’ => Mage::helper(”)->__(‘Creation Time’),
‘align’ => ‘left’,
‘width’ => ’120px’,
‘type’ => ‘date’,
‘default’ => ‘–’,
‘index’ => ‘created_time’,
));
$this->addColumn(‘update_time’, array(
‘header’ => Mage::helper(”)->__(‘Update Time’),
‘align’ => ‘left’,
‘width’ => ’120px’,
‘type’ => ‘date’,
‘default’ => ‘–’,
‘index’ => ‘update_time’,
));
$this->addColumn(‘status’, array(
‘header’ => Mage::helper(”)->__(‘Status’),
‘align’ => ‘left’,
‘width’ => ’80px’,
‘index’ => ‘status’,
‘type’ => ‘options’,
‘options’ => array(
1 => ‘Active’,
0 => ‘Inactive’,
),
));
return parent::_prepareColumns();
}
public function getRowUrl($row)
{
return $this->getUrl(‘*/*/edit’, array(‘id’ => $row->getId()));
}
public function getGridUrl()
{
return $this->getUrl(‘*/*/grid’, array(‘_current’=>true));
}
}
/app/code/local///Block/Adminhtml//Edit/Form.php
<?php
class __Block_Adminhtml__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///Block/Adminhtml//Edit/Tabs.php
<?php
class __Block_Adminhtml__Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId(‘_tabs’);
$this->setDestElementId(‘edit_form’);
$this->setTitle(Mage::helper(”)->__(‘News Information’));
}
protected function _beforeToHtml()
{
$this->addTab(‘form_section’, array(
‘label’ => Mage::helper(”)->__(‘Item Information’),
‘title’ => Mage::helper(”)->__(‘Item Information’),
‘content’ => $this->getLayout()->createBlock(‘/adminhtml__edit_tab_form’)->toHtml(),
));
return parent::_beforeToHtml();
}
}
/app/code/local///Block/Adminhtml//Edit/Tab/Form.php
<?php
class __Block_Adminhtml__Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset(‘_form’, array(‘legend’=>Mage::helper(”)->__(‘Item information’)));
$fieldset->addField(‘title’, ‘text’, array(
‘label’ => Mage::helper(”)->__(‘Title’),
‘class’ => ‘required-entry’,
‘required’ => true,
‘name’ => ‘title’,
));
$fieldset->addField(‘status’, ‘select’, array(
‘label’ => Mage::helper(”)->__(‘Status’),
‘name’ => ‘status’,
‘values’ => array(
array(
‘value’ => 1,
‘label’ => Mage::helper(”)->__(‘Active’),
),
array(
‘value’ => 0,
‘label’ => Mage::helper(”)->__(‘Inactive’),
),
),
));
$fieldset->addField(‘content’, ‘editor’, array(
‘name’ => ‘content’,
‘label’ => Mage::helper(”)->__(‘Content’),
‘title’ => Mage::helper(”)->__(‘Content’),
‘style’ => ‘width:98%; height:400px;’,
‘wysiwyg’ => false,
‘required’ => true,
));
if ( Mage::getSingleton(‘adminhtml/session’)->getData() )
{
$form->setValues(Mage::getSingleton(‘adminhtml/session’)->getData());
Mage::getSingleton(‘adminhtml/session’)->setData(null);
} elseif ( Mage::registry(‘_data’) ) {
$form->setValues(Mage::registry(‘_data’)->getData());
}
return parent::_prepareForm();
}
}
Controller
/app/code/local///controllers/Adminhtml/Controller.php
NOTE: you need to manually add line 16, which is currently missing in this file. As per suggestion from mkd at page http://www.magentocommerce.com/boards/viewthread/11228/
<?php
class __Adminhtml_Controller extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu(‘/items’)
->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Items Manager’), Mage::helper(‘adminhtml’)->__(‘Item Manager’));
return $this;
}
public function indexAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock(‘/adminhtml_’));
$this->renderLayout();
}
public function editAction()
{
$Id = $this->getRequest()->getParam(‘id’);
$Model = Mage::getModel(‘/’)->load($Id);
if ($Model->getId() || $Id == 0) {
Mage::register(‘_data’, $Model);
$this->loadLayout();
$this->_setActiveMenu(‘/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(‘/adminhtml__edit’))
->_addLeft($this->getLayout()->createBlock(‘/adminhtml__edit_tabs’));
$this->renderLayout();
} else {
Mage::getSingleton(‘adminhtml/session’)->addError(Mage::helper(”)->__(‘Item does not exist’));
$this->_redirect(‘*/*/’);
}
}
public function newAction()
{
$this->_forward(‘edit’);
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
try {
$postData = $this->getRequest()->getPost();
$Model = Mage::getModel(‘/’);
$Model->setId($this->getRequest()->getParam(‘id’))
->setTitle($postData['title'])
->setContent($postData['content'])
->setStatus($postData['status'])
->save();
Mage::getSingleton(‘adminhtml/session’)->addSuccess(Mage::helper(‘adminhtml’)->__(‘Item was successfully saved’));
Mage::getSingleton(‘adminhtml/session’)->setData(false);
$this->_redirect(‘*/*/’);
return;
} catch (Exception $e) {
Mage::getSingleton(‘adminhtml/session’)->addError($e->getMessage());
Mage::getSingleton(‘adminhtml/session’)->setData($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 {
$Model = Mage::getModel(‘/’);
$Model->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(‘*/*/’);
}
/**
* Product grid for AJAX request.
* Sort and filter result for example.
*/
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock(‘/adminhtml__grid’)->toHtml()
);
}
}
XML Configuration Changes
/app/code/local///etc/config.xml
0.1.0
standard
[Namespace]_[Module]
[module]
[module].xml
admin
[Namespace]_[Module]
[module]
200
[module].xml
[Namespace]_[Module]_Model
[module]_mysql4
[Namespace]_[Module]_Model_Mysql4
[module]
[Namespace]_[Module]
core_setup
core_write
core_read
[Namespace]_[Module]_Block
[Namespace]_[Module]_Helper
XML Layout
/app/design/adminhtml///layout/.xml
Seperate Adminhtml Configuration
It’s also worth noting the adminhtml changes in the config.xml (above) can be placed in their own XML file instead, keeping these changes separated away:
/app/code/local///etc/adminhtml.xml
200
[module].xml
Standard Magento Admin URLs, no rewrite needed
Also, rather than using a rewrite for the admin section described above, you can implement the same standard admin generated urls Magento uses. These look like: ‘/admin/[module]/index/’ instead of the above that would generate ‘/[module]/adminhtml_[module]/index/’.
To implement this different url structure you can change the following in your config.xml:
/app/code/local///etc/config.xml
…
[Namespace]_[Module]_Adminhtml
I am going to use a few common conventions here that should make it easier to figure out what you need to replace as I am making this as generic as possible.
Anything in angled brackets (including the angled brackets): , needs to replaced with the appropriate text..
Anything in square brackets (including the square brackets): [ ], needs to replaced with the appropriate text.
The reason I am using two different conventions here are that XML files already use angled brackets so you will only see the square brackets in use in XML files.
NOTE: All directory, file, class names are Case Sensitive unless otherwise noted.
Create Directories
Magento Modules follow a common naming scheme, Namespace_Module. This is very important to remember as you need to be careful about how you name your classes. Every custom module will be created in the directory:
/app/code/local
The first step in creating your custom module is determining the namespace and module name. The namespace is simply an extra division that you can create you module in. This means that you can have two modules named the same thing if they are in two different namespaces. One way to use namespaces is to use your company name or initials for all of your modules. If my company name is Acme and I am creating a module called News the full module name would be Acme_News. Magento uses the namespace Mage. There is nothing stopping you from using that namespace under local, i.e. you could create Mage_News and that would work just fine.
Note : You can not use underscore within your module name
Note2: It seems that currently, if you use upper case characters in module names (expecting to show word starts since neither – nor _ is allowed)… the install will fail or rather the module will not work. Suggestion: use a single upper case character, at the beginning of the name.
Let’s setup our directory structure:
/app/code/local///
Block/
controllers/
etc/
Model/
Mysql4/
/
sql/
_setup/
/app/design/frontend///
template/
/
Activate Module
Magento requires there to be an XML file that tells Magento to look for and use your custom module.
/app/etc/modules/_.xml
true
local
Also you can disable your module in the Configuration menu on the backend via the Advanced tab.
NOTE: Due to a bug in Magento, whitespace is not treated correctly. This means that if you leave space in the values between node names (anything in angled brackets is a node), Magento will break.
As an explanation of the above code you will see that all you are changing is the [Namespace]_[Module] text and leaving everything else the same. Please note the capital P in codePool. If this is lowercase this module will not be active.
Create Controller
/app/code/local///controllers/IndexController.php
<?php
class __IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
}
NOTE: You may notice that there is no closing, ?>, PHP tag in the code. This is a common coding style that Magento core classes use. Magento Coding Standard is similar (with some exceptions) to Zend Framework PHP Coding Standard and you can find the detailed explanations of this rule in Zend Framework Documentation
Create Configuration XML
/app/code/local///etc/config.xml
0.1.0
standard
[Namespace]_[Module]
[module]
[module].xml
[Namespace]_[Module]_Model
[module]_mysql4
[Namespace]_[Module]_Model_Mysql4
[module]
core_setup
core_write
core_read
[Namespace]_[Module]_Block
[Namespace]_[Module]_Helper
NB : You can use the frontName of your choice without any link to your module name. IE : Mage_Catalog could have “mycatalog” as a frontName.
Create Helper
/app/code/local///Helper/Data.php
<?php
class __Helper_Data extends Mage_Core_Helper_Abstract
{
}
Create Models
If you are quite new to Magento you should pay attention to one of its specifics! The Constructors below are not the usual PHP-Constructors!! Keeping that in mind can save hours of frustrating crashes
/app/code/local///Model/.php
<?php
class __Model_ extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init(‘/’);
}
}
/app/code/local///Model/Mysql4/.php
<?php
class __Model_Mysql4_ extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init(‘/’, ‘_id’);
}
}
NOTE: The ‘_id’ refers to the PRIMARY KEY in your database table.
/app/code/local///Model/Mysql4//Collection.php
<?php
class __Model_Mysql4__Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
public function _construct()
{
//parent::__construct();
$this->_init(‘/’);
}
}
SQL Setup
/app/code/local///sql/_setup/mysql4-install-0.1.0.php
startSetup();
$installer->run(”
— DROP TABLE IF EXISTS {$this->getTable(”)};
CREATE TABLE {$this->getTable(”)} (
`_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 (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
“);
$installer->endSetup();
NOTE: Please note the text that needs to be replaced. This SQL structure is up to you, this is merely a starting point.
Note Important: If you add fields and couldn’t save data in these fields please try to go to System→Cache Management Then 1.Flush Cache Storage 2.Flush Magento Cache.
Template Design
/app/design/frontend///layout/.xml
NOTE: The block type will automatically figure out what template file to use based on the second [module] declaration.
As an alternate way of declaring what template file to use you can use this: /app/design/frontend///layout/.xml
/app/design/frontend///template//.phtml
__(‘Module List’) ?>
<?php/*
This will load one record from your database table.
load(_id) will load whatever ID number you give it.
*/
/*
$news = Mage::getModel(‘/’)->load(1);
echo $news->getId();
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(‘/’)->getCollection();
$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();
}
$collection->walk(‘save’);
*/
/*
This shows how to load one value, change something and save it.
*/
/*
$object = Mage::getModel(‘/’)->load(1);
$object->setTitle(‘This is a changed title’);
$object->save();
*/
?>
NOTE: Uncomment anything that you would like to use and this is just a starting point and some common methods for you to try and pull the data out.
In this section I am utilizing the built-in Grid Widgets and form capabilities to create a form to allow editing and creating new items for your custom database.
Directory Additions
Here is the revised directory setup due to the additions and changes we need for the backend module.
/app/code/local///
Block/
Adminhtml/
/
Edit/
Tab/
controllers/
Adminhtml/
etc/
Helper/
Model/
Mysql4/
/
sql/
_setup/
Blocks
These control the setup and appearance of your grids and the options that they display.
NOTE: Please note the fact that Block comes before Adminhtml in the class declaration. In any of the Magento modules in Adminhtml it is the opposite. For your module to work it has to be Block_Adminhtml otherwise you will get a ‘Cannot redeclare module…’ error.
/app/code/local///Block/Adminhtml/.php
<?php
class __Block_Adminhtml_ extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = ‘adminhtml_’;
$this->_blockGroup = ”;
$this->_headerText = Mage::helper(”)->__(‘Item Manager’);
$this->_addButtonLabel = Mage::helper(”)->__(‘Add Item’);
parent::__construct();
}
}
/app/code/local///Block/Adminhtml//Edit.php
<?php
class __Block_Adminhtml__Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = ‘id’;
$this->_blockGroup = ”;
$this->_controller = ‘adminhtml_’;
$this->_updateButton(‘save’, ‘label’, Mage::helper(”)->__(‘Save Item’));
$this->_updateButton(‘delete’, ‘label’, Mage::helper(”)->__(‘Delete Item’));
}
public function getHeaderText()
{
if( Mage::registry(‘_data’) && Mage::registry(‘_data’)->getId() ) {
return Mage::helper(”)->__(“Edit Item ‘%s’”, $this->htmlEscape(Mage::registry(‘_data’)->getTitle()));
} else {
return Mage::helper(”)->__(‘Add Item’);
}
}
}
/app/code/local///Block/Adminhtml//Grid.php
<?php
class __Block_Adminhtml__Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId(‘Grid’);
// This is the primary key of the database
$this->setDefaultSort(‘_id’);
$this->setDefaultDir(‘ASC’);
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
protected function _prepareCollection()
{
$collection = Mage::getModel(‘/’)->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn(‘_id’, array(
‘header’ => Mage::helper(”)->__(‘ID’),
‘align’ =>’right’,
‘width’ => ’50px’,
‘index’ => ‘_id’,
));
$this->addColumn(‘title’, array(
‘header’ => Mage::helper(”)->__(‘Title’),
‘align’ =>’left’,
‘index’ => ‘title’,
));
/*
$this->addColumn(‘content’, array(
‘header’ => Mage::helper(”)->__(‘Item Content’),
‘width’ => ’150px’,
‘index’ => ‘content’,
));
*/
$this->addColumn(‘created_time’, array(
‘header’ => Mage::helper(”)->__(‘Creation Time’),
‘align’ => ‘left’,
‘width’ => ’120px’,
‘type’ => ‘date’,
‘default’ => ‘–’,
‘index’ => ‘created_time’,
));
$this->addColumn(‘update_time’, array(
‘header’ => Mage::helper(”)->__(‘Update Time’),
‘align’ => ‘left’,
‘width’ => ’120px’,
‘type’ => ‘date’,
‘default’ => ‘–’,
‘index’ => ‘update_time’,
));
$this->addColumn(‘status’, array(
‘header’ => Mage::helper(”)->__(‘Status’),
‘align’ => ‘left’,
‘width’ => ’80px’,
‘index’ => ‘status’,
‘type’ => ‘options’,
‘options’ => array(
1 => ‘Active’,
0 => ‘Inactive’,
),
));
return parent::_prepareColumns();
}
public function getRowUrl($row)
{
return $this->getUrl(‘*/*/edit’, array(‘id’ => $row->getId()));
}
public function getGridUrl()
{
return $this->getUrl(‘*/*/grid’, array(‘_current’=>true));
}
}
/app/code/local///Block/Adminhtml//Edit/Form.php
<?php
class __Block_Adminhtml__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///Block/Adminhtml//Edit/Tabs.php
<?php
class __Block_Adminhtml__Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId(‘_tabs’);
$this->setDestElementId(‘edit_form’);
$this->setTitle(Mage::helper(”)->__(‘News Information’));
}
protected function _beforeToHtml()
{
$this->addTab(‘form_section’, array(
‘label’ => Mage::helper(”)->__(‘Item Information’),
‘title’ => Mage::helper(”)->__(‘Item Information’),
‘content’ => $this->getLayout()->createBlock(‘/adminhtml__edit_tab_form’)->toHtml(),
));
return parent::_beforeToHtml();
}
}
/app/code/local///Block/Adminhtml//Edit/Tab/Form.php
<?php
class __Block_Adminhtml__Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset(‘_form’, array(‘legend’=>Mage::helper(”)->__(‘Item information’)));
$fieldset->addField(‘title’, ‘text’, array(
‘label’ => Mage::helper(”)->__(‘Title’),
‘class’ => ‘required-entry’,
‘required’ => true,
‘name’ => ‘title’,
));
$fieldset->addField(‘status’, ‘select’, array(
‘label’ => Mage::helper(”)->__(‘Status’),
‘name’ => ‘status’,
‘values’ => array(
array(
‘value’ => 1,
‘label’ => Mage::helper(”)->__(‘Active’),
),
array(
‘value’ => 0,
‘label’ => Mage::helper(”)->__(‘Inactive’),
),
),
));
$fieldset->addField(‘content’, ‘editor’, array(
‘name’ => ‘content’,
‘label’ => Mage::helper(”)->__(‘Content’),
‘title’ => Mage::helper(”)->__(‘Content’),
‘style’ => ‘width:98%; height:400px;’,
‘wysiwyg’ => false,
‘required’ => true,
));
if ( Mage::getSingleton(‘adminhtml/session’)->getData() )
{
$form->setValues(Mage::getSingleton(‘adminhtml/session’)->getData());
Mage::getSingleton(‘adminhtml/session’)->setData(null);
} elseif ( Mage::registry(‘_data’) ) {
$form->setValues(Mage::registry(‘_data’)->getData());
}
return parent::_prepareForm();
}
}
Controller
/app/code/local///controllers/Adminhtml/Controller.php
NOTE: you need to manually add line 16, which is currently missing in this file. As per suggestion from mkd at page http://www.magentocommerce.com/boards/viewthread/11228/
<?php
class __Adminhtml_Controller extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu(‘/items’)
->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Items Manager’), Mage::helper(‘adminhtml’)->__(‘Item Manager’));
return $this;
}
public function indexAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock(‘/adminhtml_’));
$this->renderLayout();
}
public function editAction()
{
$Id = $this->getRequest()->getParam(‘id’);
$Model = Mage::getModel(‘/’)->load($Id);
if ($Model->getId() || $Id == 0) {
Mage::register(‘_data’, $Model);
$this->loadLayout();
$this->_setActiveMenu(‘/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(‘/adminhtml__edit’))
->_addLeft($this->getLayout()->createBlock(‘/adminhtml__edit_tabs’));
$this->renderLayout();
} else {
Mage::getSingleton(‘adminhtml/session’)->addError(Mage::helper(”)->__(‘Item does not exist’));
$this->_redirect(‘*/*/’);
}
}
public function newAction()
{
$this->_forward(‘edit’);
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
try {
$postData = $this->getRequest()->getPost();
$Model = Mage::getModel(‘/’);
$Model->setId($this->getRequest()->getParam(‘id’))
->setTitle($postData['title'])
->setContent($postData['content'])
->setStatus($postData['status'])
->save();
Mage::getSingleton(‘adminhtml/session’)->addSuccess(Mage::helper(‘adminhtml’)->__(‘Item was successfully saved’));
Mage::getSingleton(‘adminhtml/session’)->setData(false);
$this->_redirect(‘*/*/’);
return;
} catch (Exception $e) {
Mage::getSingleton(‘adminhtml/session’)->addError($e->getMessage());
Mage::getSingleton(‘adminhtml/session’)->setData($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 {
$Model = Mage::getModel(‘/’);
$Model->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(‘*/*/’);
}
/**
* Product grid for AJAX request.
* Sort and filter result for example.
*/
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock(‘/adminhtml__grid’)->toHtml()
);
}
}
XML Configuration Changes
/app/code/local///etc/config.xml
0.1.0
standard
[Namespace]_[Module]
[module]
[module].xml
admin
[Namespace]_[Module]
[module]
200
[module].xml
[Namespace]_[Module]_Model
[module]_mysql4
[Namespace]_[Module]_Model_Mysql4
[module]
core_setup
core_write
core_read
[Namespace]_[Module]_Block
[Namespace]_[Module]_Helper
XML Layout
/app/design/adminhtml///layout/.xml
Seperate Adminhtml Configuration
It’s also worth noting the adminhtml changes in the config.xml (above) can be placed in their own XML file instead, keeping these changes separated away:
/app/code/local///etc/adminhtml.xml
200
[module].xml
Standard Magento Admin URLs, no rewrite needed
Also, rather than using a rewrite for the admin section described above, you can implement the same standard admin generated urls Magento uses. These look like: ‘/admin/[module]/index/’ instead of the above that would generate ‘/[module]/adminhtml_[module]/index/’.
To implement this different url structure you can change the following in your config.xml:
/app/code/local///etc/config.xml
…
[Namespace]_[Module]_Adminhtml
No comments:
Post a Comment