Magento1.4后台模块开发

前言

以下,均以MyModule为模块名为例。

需要注意的三大文件夹

/app/code/local

  1. 此文件夹下新建模块,结构目录如下:

|-- MyModule
|----|-- Example
|--------|-- Block
|------------|-- Adminhtml
|----------------|-- Example
|--------------------|-- Edit
|------------------------|-- Tab
|----------------------------|-- Form.php
|------------------------|-- Form.php
|------------------------|-- Tabs.php
|--------------------|-- Edit.php
|--------------------|-- Grid.php
|----------------|-- Example.php
|------------|-- Example.php
|--------|-- Helper
|------------|-- Data.php
|--------|-- Model
|------------|-- Mysql4
|----------------|-- Example
|--------------------|-- Collection.php
|----------------|-- Example.php
|------------|-- Example.php
|------------|-- Status.php
|--------|-- controllers
|------------|-- Adminhtml
|----------------|-- ExampleController.php
|------------|-- IndexController.php
|--------|-- etc
|------------|-- config.xml
|--------|-- sql
|------------|-- my_mudule_example_setup
|----------------|-- mysql-install-0.1.0.php
|----------------|-- mysql-upgrade-1.0.0-1.0.1.php
|----------------|-- mysql-upgrade-1.0.1-1.0.2.php

  1. 如下依次附上以下路径文件源码:
  • /MyModule/Example/Block/Adminhtml/Example/Edit/Tab/Form.php
<?php

class MyModule_Example_Block_Adminhtml_Example_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{

   protected function _prepareForm()
   {
       $form = new Varien_Data_Form();
       $this->setForm($form);
       $fieldset = $form->addFieldset('example_form', array('legend' => Mage::helper('example')->__('Item information')));

       $fieldset->addField('title', 'text',
           array(
           'label' => Mage::helper('example')->__('标题'),
           'required' => true,
           'name' => 'title',
       ));

       $afterElementHtml = '<p class="nm"><small>图片尺寸:1920*1440</small></p>';
       $fieldset->addField('image', 'file',
           array(
           'label' => Mage::helper('example')->__('图片'),
           'required' => false,
           'name' => 'image',
           'after_element_html' => $afterElementHtml,
       ));

       $fieldset->addField('sort', 'text',
           array(
           'label' => Mage::helper('example')->__('排序'),
           'required' => false,
           'name' => 'sort',
       ));

       $fieldset->addField('status', 'select',
           array(
           'label' => Mage::helper('example')->__('状态'),
           'name' => 'status',
           'values' => array(
               array(
                   'value' => 1,
                   'label' => Mage::helper('example')->__('Enabled'),
               ),
               array(
                   'value' => 2,
                   'label' => Mage::helper('example')->__('Disabled'),
               ),
           ),
       ));

       if (Mage::getSingleton('adminhtml/session')->getExampleData()) {
           $form->setValues(Mage::getSingleton('adminhtml/session')->getExampleData());
           Mage::getSingleton('adminhtml/session')->setExampleData(null);
       } elseif (Mage::registry('example_data')) {
           $form->setValues(Mage::registry('example_data')->getData());
       }
       return parent::_prepareForm();
   }
}
  • /MyModule/Example/Block/Adminhtml/Example/Edit/Form.php
<?php

class MyModule_Example_Block_Adminhtml_Example_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',
           'enctype' => 'multipart/form-data'
       ));

       $form->setUseContainer(true);
       $this->setForm($form);
       return parent::_prepareForm();
   }
}
  • /MyModule/Example/Block/Adminhtml/Example/Edit/Tabs.php
<?php

class MyModule_Example_Block_Adminhtml_Example_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{

   public function __construct()
   {
       parent::__construct();
       $this->setId('example_tabs');
       $this->setDestElementId('edit_form');
       $this->setTitle(Mage::helper('example')->__('Item Information'));
   }

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

       return parent::_beforeToHtml();
   }
}
  • /MyModule/Example/Block/Adminhtml/Example/Edit.php
<?php

class MyModule_Example_Block_Adminhtml_Example_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{

   public function __construct()
   {
       parent::__construct();

       $this->_objectId = 'id';
       $this->_blockGroup = 'example';
       $this->_controller = 'adminhtml_example';

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

       $this->_addButton('saveandcontinue',
           array(
           'label' => Mage::helper('adminhtml')->__('Save And Continue Edit'),
           'onclick' => 'saveAndContinueEdit()',
           'class' => 'save',
           ), -100);

       $this->_formScripts[] = "
           function toggleEditor() {
               if (tinyMCE.getInstanceById('example_content') == null) {
                   tinyMCE.execCommand('mceAddControl', false, 'example_content');
               } else {
                   tinyMCE.execCommand('mceRemoveControl', false, 'example_content');
               }
           }

           function saveAndContinueEdit(){
               editForm.submit($('edit_form').action+'back/edit/');
           }
       ";
   }

   public function getHeaderText()
   {
       if (Mage::registry('example_data') && Mage::registry('example_data')->getId()) {
           return Mage::helper('example')->__("Edit Item '%s'", $this->htmlEscape(Mage::registry('example_data')->getTitle()));
       } else {
           return Mage::helper('example')->__('Add Item');
       }
   }
}
  • /MyModule/Example/Block/Adminhtml/Example/Grid.php
<?php

class MyModule_Example_Block_Adminhtml_Example_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

   public function __construct()
   {
       parent::__construct();
       $this->setId('exampleGrid');
       $this->setDefaultSort('example_id');
       $this->setDefaultDir('ASC');
       $this->setSaveParametersInSession(true);
   }

   protected function _prepareCollection()
   {
       $model = Mage::getModel('example/example');
       $collection = $model->getCollection();

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

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

       $this->addColumn('sort',
           array(
           'header' => Mage::helper('example')->__('排序'),
           'align' => 'left',
           'width' => '60',
           'index' => 'sort',
       ));

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

       $this->addColumn('image', array(
           'header' => Mage::helper('example')->__('图片'),
           'align' => 'left',
           'index' => 'image',
       ));

       $this->addColumn('status',
           array(
           'header' => Mage::helper('example')->__('状态'),
           'align' => 'left',
           'width' => '80px',
           'index' => 'status',
           'type' => 'options',
           'options' => array(
               1 => '启用',
               2 => '禁止',
           ),
       ));

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

       $this->addExportType('*/*/exportCsv', Mage::helper('example')->__('CSV'));
       $this->addExportType('*/*/exportXml', Mage::helper('example')->__('XML'));

       return parent::_prepareColumns();
   }

   protected function _prepareMassaction()
   {
       $this->setMassactionIdField('example_id');
       $this->getMassactionBlock()->setFormFieldName('example');

       $this->getMassactionBlock()->addItem('delete',
           array(
           'label' => Mage::helper('example')->__('Delete'),
           'url' => $this->getUrl('*/*/massDelete'),
           'confirm' => Mage::helper('example')->__('Are you sure?')
       ));

       $statuses = Mage::getSingleton('example/status')->getOptionArray();

       array_unshift($statuses, array('label' => '', 'value' => ''));
       $this->getMassactionBlock()->addItem('status',
           array(
           'label' => Mage::helper('example')->__('Change status'),
           'url' => $this->getUrl('*/*/massStatus', array('_current' => true)),
           'additional' => array(
               'visibility' => array(
                   'name' => 'status',
                   'type' => 'select',
                   'class' => 'required-entry',
                   'label' => Mage::helper('example')->__('Status'),
                   'values' => $statuses
               )
           )
       ));
       return $this;
   }

   public function getRowUrl($row)
   {
       return $this->getUrl('*/*/edit', array('id' => $row->getId()));
   }
}
  • /MyModule/Example/Block/Adminhtml/Example.php
<?php

class MyModule_Example_Block_Adminhtml_Example extends Mage_Adminhtml_Block_Widget_Grid_Container
{

   public function __construct()
   {
       $this->_controller = 'adminhtml_example';
       $this->_blockGroup = 'example';
       $this->_headerText = Mage::helper('example')->__('Item Manager');
       $this->_addButtonLabel = Mage::helper('example')->__('Add Item');
       parent::__construct();
   }
}
  • /MyModule/Example/Block/Example.php
<?php

class MyModule_Example_Block_Example extends Mage_Core_Block_Template
{

   public function _prepareLayout()
   {
       return parent::_prepareLayout();
   }

   public function getHufu()
   {
       if (!$this->hasData('example')) {
           $this->setData('example', Mage::registry('example'));
       }
       return $this->getData('example');
   }
}
  • /MyModule/Example/Helper/Data.php
<?php

class MyModule_Example_Helper_Data extends Mage_Core_Helper_Abstract
{

}
  • /MyModule/Example/Model/Mysql4/Example/Collection.php
<?php

class MyModule_Example_Model_Mysql4_Example_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{

   public function _construct()
   {
       parent::_construct();
       $this->_init('example/example');
   }
}
  • /MyModule/Example/Model/Mysql4/Example.php
<?php

class MyModule_Example_Model_Mysql4_Example extends Mage_Core_Model_Mysql4_Abstract
{

   public function _construct()
   {
       $this->_init('example/example', 'example_id');
   }
}
  • /MyModule/Example/Model/Example.php
<?php

class MyModule_Example_Model_Example extends Mage_Core_Model_Abstract
{

   public function _construct()
   {
       parent::_construct();
       $this->_init('example/example');
   }
}
  • /MyModule/Example/Model/Status.php
<?php

class MyModule_Example_Model_Status extends Varien_Object
{
   const STATUS_ENABLED = 1;
   const STATUS_DISABLED = 2;

   static public function getOptionArray()
   {
       return array(
           self::STATUS_ENABLED => Mage::helper('example')->__('Enabled'),
           self::STATUS_DISABLED => Mage::helper('example')->__('Disabled')
       );
   }
}
  • /MyModule/Example/Controllers/Adminhtml/ExampleController.php
<?php

class MyModule_Example_Adminhtml_ExampleController extends Mage_Adminhtml_Controller_action
{

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

   public function indexAction()
   {
       $this->_initAction()
           ->renderLayout();
   }

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

       if ($model->getId() || $id == 0) {
           $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
           if (!empty($data)) {
               $model->setData($data);
           }

           Mage::register('example_data', $model);

           $this->loadLayout();
           $this->_setActiveMenu('example/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('example/adminhtml_example_edit'))
               ->_addLeft($this->getLayout()->createBlock('example/adminhtml_example_edit_tabs'));

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

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

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

           if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
               try {
                   /* Starting upload */
                   $uploader = new Varien_File_Uploader('image');

                   // Any extention would work
                   $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                   $uploader->setAllowRenameFiles(false);

                   // Set the file upload mode
                   // false -> get the file directly in the specified folder
                   // true -> get the file in the product like folders
                   //	(file.jpg will go in something like /media/f/i/file.jpg)
                   $uploader->setFilesDispersion(false);

                   // We set media as the upload dir
                   $path = Mage::getBaseDir('media').DS."/example/";
                   $uploader->save($path, $_FILES['image']['name']);
               } catch (Exception $e) {

               }

               //this way the name is saved in DB
               $data['image'] = $_FILES['image']['name'];
           }



           $model = Mage::getModel('example/example');
           $model->setData($data)
               ->setId($this->getRequest()->getParam('id'));

           try {
               if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
                   $model->setCreatedTime(now())
                       ->setUpdateTime(now());
               } else {
                   $model->setUpdateTime(now());
               }

               $model->save();
               Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('example')->__('Item was successfully saved'));
               Mage::getSingleton('adminhtml/session')->setFormData(false);

               if ($this->getRequest()->getParam('back')) {
                   $this->_redirect('*/*/edit', array('id' => $model->getId()));
                   return;
               }
               $this->_redirect('*/*/');
               return;
           } catch (Exception $e) {
               Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
               Mage::getSingleton('adminhtml/session')->setFormData($data);
               $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
               return;
           }
       }
       Mage::getSingleton('adminhtml/session')->addError(Mage::helper('example')->__('Unable to find item to save'));
       $this->_redirect('*/*/');
   }

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

               $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('*/*/');
   }

   public function massDeleteAction()
   {
       $exampleIds = $this->getRequest()->getParam('example');
       if (!is_array($exampleIds)) {
           Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
       } else {
           try {
               foreach ($exampleIds as $exampleId) {
                   $example = Mage::getModel('example/example')->load($exampleId);
                   $example->delete();
               }
               Mage::getSingleton('adminhtml/session')->addSuccess(
                   Mage::helper('adminhtml')->__(
                       'Total of %d record(s) were successfully deleted', count($exampleIds)
                   )
               );
           } catch (Exception $e) {
               Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
           }
       }
       $this->_redirect('*/*/index');
   }

   public function massStatusAction()
   {
       $exampleIds = $this->getRequest()->getParam('example');
       if (!is_array($exampleIds)) {
           Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
       } else {
           try {
               foreach ($exampleIds as $exampleId) {
                   $example = Mage::getSingleton('example/example')
                       ->load($exampleId)
                       ->setStatus($this->getRequest()->getParam('status'))
                       ->setIsMassupdate(true)
                       ->save();
               }
               $this->_getSession()->addSuccess(
                   $this->__('Total of %d record(s) were successfully updated', count($exampleIds))
               );
           } catch (Exception $e) {
               $this->_getSession()->addError($e->getMessage());
           }
       }
       $this->_redirect('*/*/index');
   }

   public function exportCsvAction()
   {
       $fileName = 'example.csv';
       $content = $this->getLayout()->createBlock('example/adminhtml_example_grid')
           ->getCsv();

       $this->_sendUploadResponse($fileName, $content);
   }

   public function exportXmlAction()
   {
       $fileName = 'example.xml';
       $content = $this->getLayout()->createBlock('example/adminhtml_example_grid')
           ->getXml();

       $this->_sendUploadResponse($fileName, $content);
   }

   protected function _sendUploadResponse($fileName, $content, $contentType = 'application/octet-stream')
   {
       $response = $this->getResponse();
       $response->setHeader('HTTP/1.1 200 OK', '');
       $response->setHeader('Pragma', 'public', true);
       $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
       $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
       $response->setHeader('Last-Modified', date('r'));
       $response->setHeader('Accept-Ranges', 'bytes');
       $response->setHeader('Content-Length', strlen($content));
       $response->setHeader('Content-type', $contentType);
       $response->setBody($content);
       $response->sendResponse();
       die;
   }
}
  • /MyModule/Example/Controllers/IndexController.php
<?php

class MyModule_Example_IndexController extends Mage_Core_Controller_Front_Action
{
   protected $example;

   public function indexAction()
   {
       /*
        * If no param we load a the last created item
        */
       $example = null;
       if ($example == null) {
           $resource = Mage::getSingleton('core/resource');
           $read = $resource->getConnection('core_read');
           $exampleTable = $resource->getTableName('my_module_example');

           $select = $read->select()
               ->from($exampleTable, array('example_id', 'title', 'image', 'sort', 'status'))
               ->where('status', '1')
               ->order('sort ASC');
           $example = $read->fetchAll($select);
       }
       //Mage::register('example', $example);
       //var_dump($example);

       $this->loadLayout();
       $this->renderLayout();
   }

   public function frameAction()
   {


       /*
        * If no param we load a the last created item
        */
       $example = null;
       if ($example == null) {
           $resource = Mage::getSingleton('core/resource');
           $read = $resource->getConnection('core_read');
           $exampleTable = $resource->getTableName('my_module_example');

           $select = $read->select()
               ->from($exampleTable, array('example_id', 'title', 'image', 'sort', 'status'))
               ->where('status', '1')
               ->order('sort ASC');
           $example = $read->fetchAll($select);
       }
       //Mage::register('example', $example);
       //var_dump($example);

       $this->loadLayout();
       $this->renderLayout();
   }
}
  • /MyModule/Example/etc/config.xml
<?xml version="1.0"?>
<config>
   <modules>
       <MyModule_Example>
           <version>1.0.1</version>
       </MyModule_Example>
   </modules>
   <admin>
       <routers>
           <example>
               <use>admin</use>
               <args>
                   <module>MyModule_Example</module>
                   <frontName>example</frontName>
               </args>
           </example>
       </routers>
   </admin>
   <adminhtml>
       <menu>
           <my_module module="example">
               <title>MyModule</title>
               <sort_order>72</sort_order>
           </my_module>
       </menu>
       <menu>
           <my_module>
               <children>
                   <items module="example">
                       <title>样例管理</title>
                       <sort_order>1</sort_order>
                       <action>example/adminhtml_example</action>
                   </items>
               </children>
           </my_module>
       </menu>
       <acl>
           <resources>
               <all>
                   <title>Allow Everything</title>
               </all>
               <admin>
                   <children>
                       <MyModule_Example>
                           <title>Example Module</title>
                           <sort_order>10</sort_order>
                       </MyModule_Example>
                   </children>
               </admin>
           </resources>
       </acl>
       <layout>
           <updates>
               <example>
                   <file>example.xml</file>
               </example>
           </updates>
       </layout>
   </adminhtml>
   <global>
       <models>
           <example>
               <class>MyModule_Example_Model</class>
               <resourceModel>example_mysql4</resourceModel>
           </example>
           <example_mysql4>
               <class>MyModule_Example_Model_Mysql4</class>
               <entities>
                   <example>
                       <table>my_module_example</table>
                   </example>
               </entities>
           </example_mysql4>
       </models>
       <resources>
           <my_module_example_setup>
               <setup>
                   <module>MyModule_Example</module>
               </setup>
               <connection>
                   <use>core_setup</use>
               </connection>
           </my_module_example_setup>
           <example_write>
               <connection>
                   <use>core_write</use>
               </connection>
           </example_write>
           <example_read>
               <connection>
                   <use>core_read</use>
               </connection>
           </example_read>
       </resources>
       <blocks>
           <example>
               <class>MyModule_Example_Block</class>
           </example>
       </blocks>
       <helpers>
           <example>
               <class>MyModule_Example_Helper</class>
           </example>
       </helpers>
   </global>
</config>
  • /MyModule/Example/sql/my_module_example_setup/mysql4-install-0.1.0.php
<?php
$installer = $this;

$installer->startSetup();

$installer->run("

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

");

$installer->endSetup();

/app/design/adminhtml/default/default/layout

  • 此文件夹下新建文件: example.xml
<?xml version="1.0"?>
<layout version="0.1.0">
    <example_adminhtml_example_index>
        <reference name="content">
            <block type="example/adminhtml_example" name="example" />
        </reference>
    </example_adminhtml_example_index>
</layout>

/app/etc/modules

  • 此文件夹下新建文件: my_module_example.xml
<?xml version="1.0"?>
<layout version="0.1.0">
    <example_adminhtml_example_index>
        <reference name="content">
            <block type="example/adminhtml_example" name="example" />
        </reference>
    </example_adminhtml_example_index>
</layout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值