最新消息:Excel无乱码转CSV,由于工作原因很少更新博客和回复大家的评论,非常抱歉。

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

如果你正在创建一个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

<?php
class 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

<?php

class 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

<?php

class 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

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

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

<?php

class 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

<?php

class 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>

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

下载实例:MagentoBackendModule.zip
解压密码:www.hicoogle.com

大家也可以在本文下方评论处一起交流。

转载请注明:嗨酷哥,有你更酷! » Magento创建管理列表和后台模块

与本文相关文章

发表我的评论

取消评论
表情 插代码

Hi,您需要填写昵称和邮箱!

  • 必填项
  • 必填项

网友评论1

  1. 这个应该会将数据库里面的数据直接显示出来,那么我如何对里面的数据进行编辑后再显示出来呢?比如说,数据取出来一列内容是个json的字符串,里面包含了一种产品的几个信息,但是我只想显示其中的一个,我怎么办呢?

    zxtdcyy2015-03-11 09:39 回复