Magento创建管理列表和后台模块

来源:互联网 发布:cpy什么意思网络用语 编辑:程序博客网 时间:2024/05/04 15:52

如果你正在创建一个Magento的管理模块(学习创造Magento管理模块),那么你一定会被要求创建一个管理列表既Grid。创建列表,Magento新手程序员有点困难,但在本教程中,我们将创建一个网格在管理模块中最简单的方式。
本文来自 嗨酷哥 原文:http://www.hicoogle.com/magento-to-create-a-list-and-background-module.html

空间名称:Company

模块名称:Web

注:创建模块时必要创建XMLS(这步很简单跳过)。

第一步:

创建 Web/Block/Adminhtml/Web.php

<?phpclass Company_Web_Block_Adminhtml_Web extends Mage_Adminhtml_Block_Widget_Grid_Container{  public function __construct()  {    $this->_controller = 'adminhtml_web';    $this->_blockGroup = 'web';    $this->_headerText = Mage::helper('web')->__('Item Manager');    $this->_addButtonLabel = Mage::helper('web')->__('Add Item');    parent::__construct();  }}

第二步:
创建 Web/Block/Adminhtml/Web/Grid.php

<?phpclass Company_Web_Block_Adminhtml_Web_Grid extends Mage_Adminhtml_Block_Widget_Grid{  public function __construct()  {      parent::__construct();      $this->setId('webGrid');      $this->setDefaultSort('web_id');      $this->setDefaultDir('ASC');      $this->setSaveParametersInSession(true);  }  protected function _prepareCollection()  {      $collection = Mage::getModel('web/web')->getCollection();      $this->setCollection($collection);      return parent::_prepareCollection();  }  protected function _prepareColumns()  {      $this->addColumn('web_id', array(          'header'    => Mage::helper('web')->__('ID'),          'align'     =>'right',          'width'     => '50px',          'index'     => 'web_id',      ));      $this->addColumn('title', array(          'header'    => Mage::helper('web')->__('Title'),          'align'     =>'left',          'index'     => 'title',      ));   /*      $this->addColumn('content', array(   'header'    => Mage::helper('web')->__('Item Content'),   'width'     => '150px',   'index'     => 'content',      ));   */      $this->addColumn('status', array(          'header'    => Mage::helper('web')->__('Status'),          'align'     => 'left',          'width'     => '80px',          'index'     => 'status',          'type'      => 'options',          'options'   => array(              1 => 'Enabled',              2 => 'Disabled',          ),      ));本文来自 嗨酷哥 原文:http://www.hicoogle.com/magento-to-create-a-list-and-background-module.html        $this->addColumn('action',            array(                'header'    =>  Mage::helper('web')->__('Action'),                'width'     => '100',                'type'      => 'action',                'getter'    => 'getId',                'actions'   => array(                    array(                        'caption'   => Mage::helper('web')->__('Edit'),                        'url'       => array('base'=> '*/*/edit'),                        'field'     => 'id'                    )                ),                'filter'    => false,                'sortable'  => false,                'index'     => 'stores',                'is_system' => true,        ));  $this->addExportType('*/*/exportCsv', Mage::helper('web')->__('CSV'));  $this->addExportType('*/*/exportXml', Mage::helper('web')->__('XML'));      return parent::_prepareColumns();  }    protected function _prepareMassaction()    {        $this->setMassactionIdField('web_id');        $this->getMassactionBlock()->setFormFieldName('web');        $this->getMassactionBlock()->addItem('delete', array(             'label'    => Mage::helper('web')->__('Delete'),             'url'      => $this->getUrl('*/*/massDelete'),             'confirm'  => Mage::helper('web')->__('Are you sure?')        ));        $statuses = Mage::getSingleton('web/status')->getOptionArray();        array_unshift($statuses, array('label'=>'', 'value'=>''));        $this->getMassactionBlock()->addItem('status', array(             'label'=> Mage::helper('web')->__('Change status'),             'url'  => $this->getUrl('*/*/massStatus', array('_current'=>true)),             'additional' => array(                    'visibility' => array(                         'name' => 'status',                         'type' => 'select',                         'class' => 'required-entry',                         'label' => Mage::helper('web')->__('Status'),                         'values' => $statuses                     )             )        ));        return $this;    }  public function getRowUrl($row)  {      return $this->getUrl('*/*/edit', array('id' => $row->getId()));  }}

第三步:
创建 Web/controllers/Adminhtml/WebController.php

<?phpclass Company_Web_Adminhtml_WebController extends Mage_Adminhtml_Controller_action{ protected function _initAction() {  $this->loadLayout()   ->_setActiveMenu('web/items')   ->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));  return $this; }    public function indexAction() {  $this->_initAction()   ->renderLayout(); } public function editAction() {  $id     = $this->getRequest()->getParam('id');  $model  = Mage::getModel('web/web')->load($id);  if ($model->getId() || $id == 0) {   $data = Mage::getSingleton('adminhtml/session')->getFormData(true);   if (!empty($data)) {    $model->setData($data);   }   Mage::register('web_data', $model);   $this->loadLayout();   $this->_setActiveMenu('web/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('web/adminhtml_web_edit'))    ->_addLeft($this->getLayout()->createBlock('web/adminhtml_web_edit_tabs'));   $this->renderLayout();  } else {   Mage::getSingleton('adminhtml/session')->addError(Mage::helper('web')->__('Item does not exist'));   $this->_redirect('*/*/');  } }本文来自 嗨酷哥 原文:http://www.hicoogle.com/magento-to-create-a-list-and-background-module.html public function newAction() {  $this->_forward('edit'); } public function saveAction() {  if ($data = $this->getRequest()->getPost()) {   if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {    try {     /* Starting upload */     $uploader = new Varien_File_Uploader('filename');     // 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 ;     $uploader->save($path, $_FILES['filename']['name'] );    } catch (Exception $e) {          }          //this way the name is saved in DB      $data['filename'] = $_FILES['filename']['name'];   }   $model = Mage::getModel('web/web');   $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('web')->__('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('web')->__('Unable to find item to save'));        $this->_redirect('*/*/'); } public function deleteAction() {  if( $this->getRequest()->getParam('id') > 0 ) {   try {    $model = Mage::getModel('web/web');    $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() {        $webIds = $this->getRequest()->getParam('web');        if(!is_array($webIds)) {   Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));        } else {            try {                foreach ($webIds as $webId) {                    $web = Mage::getModel('web/web')->load($webId);                    $web->delete();                }                Mage::getSingleton('adminhtml/session')->addSuccess(                    Mage::helper('adminhtml')->__(                        'Total of %d record(s) were successfully deleted', count($webIds)                    )                );            } catch (Exception $e) {                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());            }        }        $this->_redirect('*/*/index');    }    public function massStatusAction()    {        $webIds = $this->getRequest()->getParam('web');        if(!is_array($webIds)) {            Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));        } else {            try {                foreach ($webIds as $webId) {                    $web = Mage::getSingleton('web/web')                        ->load($webId)                        ->setStatus($this->getRequest()->getParam('status'))                        ->setIsMassupdate(true)                        ->save();                }                $this->_getSession()->addSuccess(                    $this->__('Total of %d record(s) were successfully updated', count($webIds))                );            } catch (Exception $e) {                $this->_getSession()->addError($e->getMessage());            }        }        $this->_redirect('*/*/index');    }本文来自 嗨酷哥 原文:http://www.hicoogle.com/magento-to-create-a-list-and-background-module.html}

第四步:
创建 Web/Model/Web.php

<?phpclass Company_Web_Model_Web extends Mage_Core_Model_Abstract{    public function _construct()    {        parent::_construct();        $this->_init('web/web');    }}

第五步:
创建 Web/Model/Mysql4/Web.php

<?phpclass Company_Web_Model_Mysql4_Web extends Mage_Core_Model_Mysql4_Abstract{    public function _construct()    {        $this->_init('web/web', 'web_id');    }}

第六步:
创建 Web/Model/Mysql4/Web/Collection.php

<?phpclass Company_Web_Model_Mysql4_Web_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract{    public function _construct()    {        parent::_construct();        $this->_init('web/web');    }}

你的列表还不会出现在后台,必须要创建下面的XML文件。

第七步:
创建 app/design/adminhtml/default/default/layout/web.xml

<?php<?xml version="1.0"?><layout version="0.1.0">    <web_adminhtml_web_index>        <reference name="content">            <block type="web/adminhtml_web" name="web" />        </reference>    </web_adminhtml_web_index></layout>

好了,先介绍到这里,你可以下载这个文件,然后慢慢研究。

有实例下载,请到http://download.csdn.net/detail/hicoogle/4259774

原文:http://www.hicoogle.com/magento-to-create-a-list-and-background-module.html

原创粉丝点击