文档章节

magento新闻模块开发(二)

xinson
 xinson
发布于 2015/10/12 13:35
字数 1339
阅读 100
收藏 0

Magento提供了强大的Grid Widget使我们能够方便的创建数据表格,现在我们为新闻模块创建后台数据表格。

修改config.xml配置文件,添加admin路由

<config>
    <admin>
        <routers>
            <news>
                <use>admin</use>
                <args>
                    <module>Xinson_News</module>
                    <frontName>news</frontName>
                </args>
            </news>
        </routers>
    </admin>
</config>


添加后台菜单

/app/code/local/Xinson/News/etc/adminhtml.xml 加到cms菜单里面。

<?xml version="1.0"?>
<config>
    <menu>
        <cms>
            <children>
                <news translate="title" module="news">
                    <title>News</title>
                    <action>news/adminhtml_news</action>
                    <sort_order>40</sort_order>
                </news>
            </children>
        </cms>
    </menu>
    <acl>
        <resources>
            <admin>
                <children>
                    <cms>
                        <children>
                            <news translate="title" module="news">
                                <title>News</title>
                                <sort_order>40</sort_order>
                            </news>
                        </children>
                    </cms>
                </children>
            </admin>
        </resources>
    </acl>
</config>


添加Grid表格

后台控制器indexAction

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

<?php

class Xinson_News_Adminhtml_NewsController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    {
        $this->_title($this->__('CMS'))->_title($this->__('News'));

        $this->loadLayout();
        $this->_setActiveMenu('cms/news');//当前选中状态
        $this->_addBreadcrumb(Mage::helper('adminhtml')->__('News Manager'), Mage::helper('adminhtml')->__('News Manager'));//Mage::helper('adminhtml')->__ 这样是访问语言包  $this->__addBreadcrumb

        $this->_addContent($this->getLayout()->createBlock('news/adminhtml_news'));//增加block
        $this->renderLayout();
    }
}

添加Block

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

<?php

class Xinson_News_Block_Adminhtml_News extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        $this->_controller = 'adminhtml_news'; //就是 Adminhtml/NewsController.php
        $this->_blockGroup = 'news'; //这是block组
        $this->_headerText = Mage::helper('news')->__('News Manager');
        $this->_addButtonLabel = Mage::helper('news')->__('Add News');
        parent::__construct();
    }
}

添加grid文件

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

<?php

class Xinson_News_Block_Adminhtml_News_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('newsGrid');
        $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('is_active', array(
            'header' => Mage::helper('news')->__('Status'),
            'align' => 'left',
            'width' => '80px',
            'index' => 'is_active',
            'type' => 'options',
            'options' => Mage::getSingleton('news/news')->getAvailableStatuses(),
        ));

        $this->addColumn('created_at', array(
            'header' => Mage::helper('news')->__('Created At'),
            'align' =>'left',
            'width' => '180px',
            'type' => 'datetime',
            'index' => 'created_at',
        ));

        $this->addColumn('updated_at', array(
            'header' => Mage::helper('news')->__('Updated At'),
            'align' =>'left',
            'width' => '180px',
            'type' => 'datetime',
            'index' => 'updated_at',
        ));

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

        return parent::_prepareColumns();
    }

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

由于 _prepareColumns有 Mage::getSingleton('news/news')->getAvailableStatuses() 

在 /app/code/local/Xinson/News/Model/News.php中添加getAvailableStatuses()方法

<?php

class Xinson_News_Model_News extends Mage_Core_Model_Abstract
{
    //....

    const STATUS_ENABLED = 1;
    const STATUS_DISABLED = 0;

    public function getAvailableStatuses()
    {
        $statuses = new Varien_Object(array(
            self::STATUS_ENABLED => Mage::helper('news')->__('Enabled'),
            self::STATUS_DISABLED => Mage::helper('news')->__('Disabled'),
        ));

        return $statuses->getData();
    }
}


新闻模块创建和编辑

添加后台控制器的newAction和editAction方法

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

<?php

class Xinson_News_Adminhtml_NewsController extends Mage_Adminhtml_Controller_Action
{
    //...

    public function newAction()
    {
        $this->getRequest()->setParam('id', 0);
        $this->_forward('edit');
    }
    
    public function editAction()
    {
        $this->_title($this->__('CMS'))->_title($this->__('News'));
        
        $newsId = $this->getRequest()->getParam('id');
        $newsModel = Mage::getModel('news/news')->load($newsId);

        if ($newsModel->getId() || $newsId == 0) {
            $this->_title($newsModel->getId() ? $newsModel->getTitle() : $this->__('New News'));
            
            Mage::register('news_data', $newsModel);
            
            $this->loadLayout();
            $this->_setActiveMenu('cms/news');
            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('News Manager'), Mage::helper('adminhtml')->__('News Manager'), $this->getUrl('*/*/'));
            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Edit News'), Mage::helper('adminhtml')->__('Edit 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')->__('The news does not exist.'));
            $this->_redirect('*/*/');
        }
    }
}


添加Form Container

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

<?php

class Xinson_News_Block_Adminhtml_News_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        $this->_objectId = 'id';
        $this->_blockGroup = 'news';
        $this->_controller = 'adminhtml_news';

        parent::__construct();
        //更新按钮文字
        $this->_updateButton('save', 'label', Mage::helper('news')->__('Save News'));
        $this->_updateButton('delete', 'label', Mage::helper('news')->__('Delete News'));
    }

    public function getHeaderText()
    {
        //判断区分 新增和编辑
        if(Mage::registry('news_data') && Mage::registry('news_data')->getId()) {
            return Mage::helper('news')->__("Edit News '%s'", $this->htmlEscape(Mage::registry('news_data')->getTitle()));
        } else {
            return Mage::helper('news')->__('Add News');
        }
    }
}


添加Form

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

<?php

class Xinson_News_Block_Adminhtml_News_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    //编辑的form的参数,action地址
    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();
    }
}


添加Tabs

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

<?php
//这是左边栏
class Xinson_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')->__('News Information'),
            'title' => Mage::helper('news')->__('News Information'),
            'content' => $this->getLayout()->createBlock('news/adminhtml_news_edit_tabs_form')->toHtml(),
        ));

        return parent::_beforeToHtml();
    }
}


 添加Tab Form

/app/code/local/Xinson/News/Block/Adminhtml/News/Edit/Tabs/Form.php

<?php
//这是编辑区
class Xinson_News_Block_Adminhtml_News_Edit_Tabs_Form extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
        $model = Mage::registry('news_data');
        
        $form = new Varien_Data_Form();

        $fieldset = $form->addFieldset('news_form', array('legend'=>Mage::helper('news')->__('News information')));
        
        if ($model->getNewsId()) {
            $fieldset->addField('news_id', 'hidden', array(
                'name' => 'news_id',
            ));
        }
        $fieldset->addField('title', 'text', array(
            'name' => 'title',
            'label' => Mage::helper('news')->__('News Title'),
            'title' => Mage::helper('news')->__('News Title'),
            'required' => true,
        ));
        
        $fieldset->addField('is_active', 'select', array(
            'name' => 'is_active',
            'label' => Mage::helper('news')->__('Status'),
            'title' => Mage::helper('news')->__('News Status'),
            'required' => true,
            'options' => $model->getAvailableStatuses(),
        ));

        $fieldset->addField('content', 'editor', array(
            'name' => 'content',
            'label' => Mage::helper('news')->__('Content'),
            'title' => Mage::helper('news')->__('Content'),
            'required' => true,
            'style' => 'width:700px; height:300px;',
        ));

        $form->setValues($model->getData());
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

刷新后台页面,点击Add News按钮新建新闻或点击表格中的某一行编辑新闻,观察是否显示编辑表单,下面我们为表单添加保存和删除的功能。


后台控制器的saveAction和deleteAction

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

<?php

class Xinson_News_Adminhtml_NewsController extends Mage_Adminhtml_Controller_Action
{
    //...
    
    public function saveAction()
    {
        if ($data = $this->getRequest()->getPost()) {
        
            $id = $this->getRequest()->getParam('id');
            $model = Mage::getModel('news/news')->load($id);
            if (!$model->getId() && $id) {
                Mage::getSingleton('adminhtml/session')->addError(Mage::helper('news')->__('This news no longer exists.'));
                $this->_redirect('*/*/');
                return;
            }
            
            if ($model->getCreatedAt() == NULL || $model->getUpdatedAt() == NULL) {
                $data['created_at'] = now();
                $data['updated_at'] = now();
            } else {
                $data['updated_at'] = now();
            }
            $model->setData($data);
            
            try {
                $model->save();
                
                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('news')->__('The news has been saved.'));
                
                Mage::getSingleton('adminhtml/session')->setFormData(false);
                
                if ($this->getRequest()->getParam('back')) {
                    $this->_redirect('*/*/edit', array('id' => $model->getId(), '_current'=>true));
                    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;
            }
        }
        $this->_redirect('*/*/');
    }
    
    public function deleteAction()
    {
        if ($id = $this->getRequest()->getParam('id')) {
            try {
                $model = Mage::getModel('news/news');
                $model->setId($id);
                $model->delete();
                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('news')->__('The news has been deleted.'));
                $this->_redirect('*/*/');
                return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('news')->__('Unable to find a news to delete.'));
        $this->_redirect('*/*/');
    }
}


© 著作权归作者所有

共有 人打赏支持
xinson
粉丝 15
博文 133
码字总数 29814
作品 0
广州
程序员
Magento2, 我们在等你

文章前面我要说明,Magento2.0和1.X是完全不同的两个版本.简单来说,magento2.0完全是重构的.完全的不同,彻底的不同.记住哦,这是magento贰 git获得magento2源码:https://github.com/magento/m...

蟋蟀哥哥
2011/12/16
11.1K
18
magento新闻模块开发(一)

Magento模块开发的简单示例 开发模式下开启日志记录,方便调试。 System->Developer magento/var 要开启777权限,/var/log目录下能看到(exception.log,system.log)。 模块文件 (Xinson 为P...

xinson
2015/10/12
77
0
Magento微信登陆模块 / Magento微信联合登陆 / 支持Magento 1.9.X

原文:Magento微信登陆模块,支持Magento1.9.X 关于Alipaymate 2012年以来,Alipaymate一直专注于支付宝接口开发集成,以及微信支付、网银在线、Paypal、财付通、Global Connect 国际信用卡支...

Alipaymate
2015/11/24
784
1
Magento微信跨境支付模块V2.1发布

关于微信跨境支付(WeChat Cross-border Payment) 微信跨境支付的核心功能是实现“人民币收款,向境外商家结算外币”。微信支付已支持:英镑、港币、美元、日元、加拿大元、澳大利亚元、欧元、...

Alipaymate
2015/11/21
0
1
magento性能优化策略大全

magento的网站实在是太慢了,想了好多办法,参考了好多资料,做了很多测试,总结一下大概的步骤如下 (继续) : 1、压缩js,css代码,如果有必要把所有的css,js分别综合到一个文件中,并压缩...

rio
2010/05/07
0
3

没有更多内容

加载失败,请刷新页面

加载更多

下一页

咕泡-Factory设计模式笔记

简单工厂模式(Factory) 做静态工厂方法(StaticFactory Method)模式,但不属于23 种设计模式之一 简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类 Spring...

职业搬砖20年
13分钟前
0
0
Java中的锁分类

在读很多并发文章中,会提及各种各样锁如公平锁,乐观锁等等,这篇文章介绍各种锁的分类。介绍的内容如下: 公平锁/非公平锁 可重入锁 独享锁/共享锁 互斥锁/读写锁 乐观锁/悲观锁 分段锁 偏...

Funcy1122
21分钟前
0
0
Ansible随机数

想为你的Ansible剧本取一个随机数?还想在接下来的运行中保持系统的等幂性?这里有一个答案。 假如,你要为一大批服务器设置cron任务,却不想让它们同时启动,你可以这样设置分钟数: minute...

大别阿郎
31分钟前
0
0
SpringCloud之服务注册中心Eureka

本系列介绍的配置均基于 Spring Boot 2.0.1.RELEASE 版本和 Spring Cloud Finchley.SR1 服务注册中心 Spring Cloud 已经帮我们实现了服务注册中心,我们只需要很简单的几个步骤就可以完成。 ...

熊小飞呀
58分钟前
7
1
“Comparison method violates ...”异常的再现方法

前提条件:JDK8 代码: import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Test { public stat......

hunterli
今天
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部