EAV 엔터티를 만드는 방법은 무엇입니까?
이것은 웹에서 많이 나타나는 질문입니다. 그 방법을 설명하는 좋은 블로그 기사가 있지만 그중 어느 것도 나를 만족시키지 않습니다.
그래서 나는 스스로 대답하는 질문으로 결정하고 어떻게하는지 설명했습니다 ... 그리고 그것은 효과가있는 것 같습니다.
여기에 많은 코드가 있습니다. 정답을 올바르게 읽으려면 '가장 오래된 것'으로 답을 정렬하십시오.
EAV 엔터티를 만드는 방법은 무엇입니까?
이것은 웹에서 많이 나타나는 질문입니다. 그 방법을 설명하는 좋은 블로그 기사가 있지만 그중 어느 것도 나를 만족시키지 않습니다.
그래서 나는 스스로 대답하는 질문으로 결정하고 어떻게하는지 설명했습니다 ... 그리고 그것은 효과가있는 것 같습니다.
여기에 많은 코드가 있습니다. 정답을 올바르게 읽으려면 '가장 오래된 것'으로 답을 정렬하십시오.
답변:
1 부
이 데모를 위해 모듈을 만들겠습니다 . Easylife_News
라는 엔티티가 포함 된 모듈을 이름을 지정하겠습니다 Article
.
이 모듈에는 속성 관리 섹션과 각 기사에 대한 간단한 프론트 엔드 목록 및보기 페이지를 포함하여 백엔드 용 완전한 CRUD 코드가 제공됩니다. 또한 상단 메뉴의 메뉴 항목을 기사 목록에 광고합니다.
또한 프런트 엔드 용 URL 다시 쓰기, RSS 피드 및 이동 경로가 포함되어 있습니다. 이 단체는 4 개 특성을 갖습니다 : Title, Short Description, Description, Publish Date
시스템들에 추가하여 ( created_at
, updated_at
, status
, in_rss
, url_key
).
모듈은 다음 파일을 포함해야합니다.
app/etc/module/Easylife_News.xml
-신고 모듈 :
<?xml version="1.0"?>
<config>
<modules>
<Easylife_News>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Catalog /><!-- some classes extend one class from the catalog module to avoid duplicating it -->
</depends>
</Easylife_News>
</modules>
</config>
app/code/local/Easylife/News/etc/config.xml
-구성 파일
<?xml version="1.0"?>
<config>
<modules>
<Easylife_News>
<version>1.0.0</version>
</Easylife_News>
</modules>
<global>
<resources>
<easylife_news_setup>
<setup>
<module>Easylife_News</module>
<class>Easylife_News_Model_Resource_Setup</class>
</setup>
</easylife_news_setup>
</resources>
<blocks>
<easylife_news>
<class>Easylife_News_Block</class>
</easylife_news>
</blocks>
<helpers>
<easylife_news>
<class>Easylife_News_Helper</class>
</easylife_news>
</helpers>
<models>
<easylife_news>
<class>Easylife_News_Model</class>
<resourceModel>easylife_news_resource</resourceModel>
</easylife_news>
<easylife_news_resource>
<class>Easylife_News_Model_Resource</class>
<entities>
<article>
<table>easylife_news_article</table>
</article>
<eav_attribute>
<table>easylife_news_eav_attribute</table>
</eav_attribute>
</entities>
</easylife_news_resource>
</models>
<events>
<controller_front_init_routers><!-- event for custom router - url rewrites -->
<observers>
<easylife_news>
<class>Easylife_News_Controller_Router</class>
<method>initControllerRouters</method>
</easylife_news>
</observers>
</controller_front_init_routers>
</events>
</global>
<adminhtml>
<layout>
<updates>
<easylife_news>
<file>easylife_news.xml</file>
</easylife_news>
</updates>
</layout>
<translate>
<modules>
<Easylife_News>
<files>
<default>Easylife_News.csv</default>
</files>
</Easylife_News>
</modules>
</translate>
<global_search>
<article>
<class>easylife_news/adminhtml_search_article</class>
<acl>easylife_news</acl>
</article>
</global_search>
</adminhtml>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<Easylife_News before="Mage_Adminhtml">Easylife_News_Adminhtml</Easylife_News>
</modules>
</args>
</adminhtml>
</routers>
</admin>
<frontend>
<events>
<page_block_html_topmenu_gethtml_before><!-- add link to top menu -->
<observers>
<easylife_news>
<class>easylife_news/observer</class>
<method>addItemsToTopmenuItems</method>
</easylife_news>
</observers>
</page_block_html_topmenu_gethtml_before>
</events>
<routers>
<easylife_news>
<use>standard</use>
<args>
<module>Easylife_News</module>
<frontName>news</frontName>
</args>
</easylife_news>
</routers>
<layout>
<updates>
<easylife_news>
<file>easylife_news.xml</file>
</easylife_news>
</updates>
</layout>
<translate>
<modules>
<Easylife_News>
<files>
<default>Easylife_News.csv</default>
</files>
</Easylife_News>
</modules>
</translate>
</frontend>
<default>
<easylife_news>
<article>
<breadcrumbs>1</breadcrumbs>
<url_prefix>article</url_prefix>
<url_suffix>html</url_suffix>
<rss>1</rss>
<meta_title>Articles</meta_title>
</article>
</easylife_news>
</default>
</config>
app/code/local/Easylife/News/etc/adminhtml.xml
-관리자 acl 및 메뉴 파일.
<?xml version="1.0"?>
<config>
<acl>
<resources>
<admin>
<children>
<system>
<children>
<config>
<children>
<easylife_news translate="title" module="easylife_news">
<title>News</title>
</easylife_news>
</children>
</config>
</children>
</system>
<cms>
<children>
<easylife_news translate="title" module="easylife_news">
<title>News</title>
<children>
<article translate="title" module="easylife_news">
<title>Article</title>
<sort_order>0</sort_order>
</article>
<article_attributes translate="title" module="easylife_news">
<title>Manage Article attributes</title>
<sort_order>7</sort_order>
</article_attributes>
</children>
</easylife_news>
</children>
</cms>
</children>
</admin>
</resources>
</acl>
<menu>
<cms><!-- I added the admin menu under CMS. Feel free to move it. -->
<children>
<easylife_news translate="title" module="easylife_news">
<title>News</title>
<sort_order>17</sort_order>
<children>
<article translate="title" module="easylife_news">
<title>Article</title>
<action>adminhtml/news_article</action>
<sort_order>0</sort_order>
</article>
<article_attributes translate="title" module="easylife_news">
<title>Manage Article Attributes</title>
<action>adminhtml/news_article_attribute</action>
<sort_order>7</sort_order>
</article_attributes>
</children>
</easylife_news>
</children>
</cms>
</menu>
</config>
app/code/local/Easylife/News/etc/system.xml
-시스템 구성 파일. 그것은 당신이 기사 목록, 빵 부스러기, RSS 활성화 / 비활성화, URL 접두사 및 접미사에 대한 SEO와 같은 몇 가지 설정을 관리 할 수 있습니다
<?xml version="1.0"?>
<config>
<tabs>
<easylife translate="label" module="easylife_news">
<label>News</label>
<sort_order>2000</sort_order>
</easylife>
</tabs>
<sections>
<easylife_news translate="label" module="easylife_news">
<class>separator-top</class>
<label>News</label>
<tab>easylife</tab>
<frontend_type>text</frontend_type>
<sort_order>100</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<groups>
<article translate="label" module="easylife_news">
<label>Article</label>
<frontend_type>text</frontend_type>
<sort_order>0</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<breadcrumbs translate="label">
<label>Use Breadcrumbs</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</breadcrumbs>
<url_prefix translate="label comment">
<label>URL prefix</label>
<frontend_type>text</frontend_type>
<sort_order>20</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<comment>Leave empty for no prefix</comment>
</url_prefix>
<url_suffix translate="label comment">
<label>Url suffix</label>
<frontend_type>text</frontend_type>
<sort_order>30</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<comment>What goes after the dot. Leave empty for no suffix.</comment>
</url_suffix>
<rss translate="label">
<label>Enable rss</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>40</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</rss>
<meta_title translate="label">
<label>Meta title for articles list page</label>
<frontend_type>text</frontend_type>
<sort_order>50</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_title>
<meta_description translate="label">
<label>Meta description for articles list page</label>
<frontend_type>textarea</frontend_type>
<sort_order>60</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_description>
<meta_keywords translate="label">
<label>Meta keywords for articles list page</label>
<frontend_type>textarea</frontend_type>
<sort_order>70</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_keywords>
</fields>
</article>
</groups>
</easylife_news>
</sections>
</config>
app/code/local/Easylife/News/sql/easylife_news_setup/install-1.0.0.php
-설치 스크립트
<?php
$this->startSetup();
//create the entity table
$table = $this->getConnection()
->newTable($this->getTable('easylife_news/article'))
->addColumn('entity_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'identity' => true,
'unsigned' => true,
'nullable' => false,
'primary' => true,
), 'Entity ID')
->addColumn('entity_type_id', Varien_Db_Ddl_Table::TYPE_SMALLINT, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Entity Type ID')
->addColumn('attribute_set_id', Varien_Db_Ddl_Table::TYPE_SMALLINT, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Attribute Set ID')
->addColumn('created_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array(
), 'Creation Time')
->addColumn('updated_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array(
), 'Update Time')
->addIndex($this->getIdxName('easylife_news/article', array('entity_type_id')),
array('entity_type_id'))
->addIndex($this->getIdxName('easylife_news/article', array('attribute_set_id')),
array('attribute_set_id'))
->addForeignKey(
$this->getFkName(
'easylife_news/article',
'attribute_set_id',
'eav/attribute_set',
'attribute_set_id'
),
'attribute_set_id', $this->getTable('eav/attribute_set'), 'attribute_set_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->addForeignKey($this->getFkName('easylife_news/article', 'entity_type_id', 'eav/entity_type', 'entity_type_id'),
'entity_type_id', $this->getTable('eav/entity_type'), 'entity_type_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->setComment('Article Table');
$this->getConnection()->createTable($table);
//create the attribute values tables (int, decimal, varchar, text, datetime)
$articleEav = array();
$articleEav['int'] = array(
'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
'length' => null,
'comment' => 'Article Datetime Attribute Backend Table'
);
$articleEav['varchar'] = array(
'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
'length' => 255,
'comment' => 'Article Varchar Attribute Backend Table'
);
$articleEav['text'] = array(
'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
'length' => '64k',
'comment' => 'Article Text Attribute Backend Table'
);
$articleEav['datetime'] = array(
'type' => Varien_Db_Ddl_Table::TYPE_DATETIME,
'length' => null,
'comment' => 'Article Datetime Attribute Backend Table'
);
$articleEav['decimal'] = array(
'type' => Varien_Db_Ddl_Table::TYPE_DECIMAL,
'length' => '12,4',
'comment' => 'Article Datetime Attribute Backend Table'
);
foreach ($articleEav as $type => $options) {
$table = $this->getConnection()
->newTable($this->getTable(array('easylife_news/article', $type)))
->addColumn('value_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'identity' => true,
'nullable' => false,
'primary' => true,
), 'Value ID')
->addColumn('entity_type_id', Varien_Db_Ddl_Table::TYPE_SMALLINT, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Entity Type ID')
->addColumn('attribute_id', Varien_Db_Ddl_Table::TYPE_SMALLINT, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Attribute ID')
->addColumn('store_id', Varien_Db_Ddl_Table::TYPE_SMALLINT, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Store ID')
->addColumn('entity_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Entity ID')
->addColumn('value', $options['type'], $options['length'], array(
), 'Value')
->addIndex(
$this->getIdxName(
array('easylife_news/article', $type),
array('entity_id', 'attribute_id', 'store_id'),
Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
),
array('entity_id', 'attribute_id', 'store_id'),
array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE))
->addIndex($this->getIdxName(array('easylife_news/article', $type), array('store_id')),
array('store_id'))
->addIndex($this->getIdxName(array('easylife_news/article', $type), array('entity_id')),
array('entity_id'))
->addIndex($this->getIdxName(array('easylife_news/article', $type), array('attribute_id')),
array('attribute_id'))
->addForeignKey(
$this->getFkName(
array('easylife_news/article', $type),
'attribute_id',
'eav/attribute',
'attribute_id'
),
'attribute_id', $this->getTable('eav/attribute'), 'attribute_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->addForeignKey(
$this->getFkName(
array('easylife_news/article', $type),
'entity_id',
'easylife_news/article',
'entity_id'
),
'entity_id', $this->getTable('easylife_news/article'), 'entity_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->addForeignKey($this->getFkName(array('easylife_news/article', $type), 'store_id', 'core/store', 'store_id'),
'store_id', $this->getTable('core/store'), 'store_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
->setComment($options['comment']);
$this->getConnection()->createTable($table);
}
//crete the news_eav_attribute (for additional attribute settings)
$table = $this->getConnection()
->newTable($this->getTable('easylife_news/eav_attribute'))
->addColumn('attribute_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'identity' => true,
'nullable' => false,
'primary' => true,
), 'Attribute ID')
->addColumn('is_global', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(), 'Attribute scope')
->addColumn('position', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(), 'Attribute position')
->addColumn('is_wysiwyg_enabled', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(), 'Attribute uses WYSIWYG')
->addColumn('is_visible', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(), 'Attribute is visible')
->setComment('News attribute table');
$this->getConnection()->createTable($table);
$this->installEntities();
$this->endSetup();
모델
app/code/local/Easylife/News/Model/Observer.php
-상단 메뉴에 새 메뉴 항목을 추가하십시오.
<?php
class Easylife_News_Model_Observer {
public function addItemsToTopmenuItems($observer) {
$menu = $observer->getMenu();
$tree = $menu->getTree();
$action = Mage::app()->getFrontController()->getAction()->getFullActionName();
$articleNodeId = 'article';
$data = array(
'name' => Mage::helper('easylife_news')->__('Articles'),
'id' => $articleNodeId,
'url' => Mage::helper('easylife_news/article')->getArticlesUrl(),
'is_active' => ($action == 'easylife_news_article_index' || $action == 'easylife_news_article_view')
);
$articleNode = new Varien_Data_Tree_Node($data, 'id', $tree, $menu);
$menu->addChild($articleNode);
return $this;
}
}
app/code/local/Easylife/News/Model/Article.php
-기사 주요 모델
<?php
class Easylife_News_Model_Article
extends Mage_Catalog_Model_Abstract {
const ENTITY = 'easylife_news_article';
const CACHE_TAG = 'easylife_news_article';
protected $_eventPrefix = 'easylife_news_article';
protected $_eventObject = 'article';
public function _construct(){
parent::_construct();
$this->_init('easylife_news/article');
}
protected function _beforeSave(){
parent::_beforeSave();
$now = Mage::getSingleton('core/date')->gmtDate();
if ($this->isObjectNew()){
$this->setCreatedAt($now);
}
$this->setUpdatedAt($now);
return $this;
}
public function getArticleUrl(){
if ($this->getUrlKey()){
$urlKey = '';
if ($prefix = Mage::getStoreConfig('easylife_news/article/url_prefix')){
$urlKey .= $prefix.'/';
}
$urlKey .= $this->getUrlKey();
if ($suffix = Mage::getStoreConfig('easylife_news/article/url_suffix')){
$urlKey .= '.'.$suffix;
}
return Mage::getUrl('', array('_direct'=>$urlKey));
}
return Mage::getUrl('easylife_news/article/view', array('id'=>$this->getId()));
}
public function checkUrlKey($urlKey, $active = true){
return $this->_getResource()->checkUrlKey($urlKey, $active);
}
public function getDescription(){ //this needs to be implemented for all WYSIWYG attributes
$description = $this->getData('description');
$helper = Mage::helper('cms');
$processor = $helper->getBlockTemplateProcessor();
$html = $processor->filter($description);
return $html;
}
public function getDefaultAttributeSetId() {
return $this->getResource()->getEntityType()->getDefaultAttributeSetId();
}
public function getAttributeText($attributeCode) {
$text = $this->getResource()
->getAttribute($attributeCode)
->getSource()
->getOptionText($this->getData($attributeCode));
if (is_array($text)){
return implode(', ',$text);
}
return $text;
}
public function getDefaultValues() {
$values = array();
$values['status'] = 1;
$values['in_rss'] = 1;
return $values;
}
}
app/code/local/Easylife/News/Model/Resource/Article.php
-기사의 자원 모델
<?php
class Easylife_News_Model_Resource_Article
extends Mage_Catalog_Model_Resource_Abstract {
public function __construct() {
$resource = Mage::getSingleton('core/resource');
$this->setType('easylife_news_article')
->setConnection(
$resource->getConnection('article_read'),
$resource->getConnection('article_write')
);
}
public function getMainTable() {
return $this->getEntityTable();
}
public function checkUrlKey($urlKey, $storeId, $active = true){
$stores = array(Mage_Core_Model_App::ADMIN_STORE_ID, $storeId);
$select = $this->_initCheckUrlKeySelect($urlKey, $stores);
if (!$select){
return false;
}
$select->reset(Zend_Db_Select::COLUMNS)
->columns('e.entity_id')
->limit(1);
return $this->_getReadAdapter()->fetchOne($select);
}
protected function _initCheckUrlKeySelect($urlKey, $store){
$urlRewrite = Mage::getModel('eav/config')->getAttribute('easylife_news_article', 'url_key');
if (!$urlRewrite || !$urlRewrite->getId()){
return false;
}
$table = $urlRewrite->getBackend()->getTable();
$select = $this->_getReadAdapter()->select()
->from(array('e' => $table))
->where('e.attribute_id = ?', $urlRewrite->getId())
->where('e.value = ?', $urlKey)
->where('e.store_id IN (?)', $store)
->order('e.store_id DESC');
return $select;
}
}
app/code/local/Easylife/News/Model/Resource/Article/Collection.php
-수집 모델
<?php
class Easylife_News_Model_Resource_Article_Collection
extends Mage_Catalog_Model_Resource_Collection_Abstract {
protected function _construct(){
parent::_construct();
$this->_init('easylife_news/article');
}
protected function _toOptionArray($valueField='entity_id', $labelField='title', $additional=array()){
$this->addAttributeToSelect('title');
return parent::_toOptionArray($valueField, $labelField, $additional);
}
protected function _toOptionHash($valueField='entity_id', $labelField='title'){
$this->addAttributeToSelect('title');
return parent::_toOptionHash($valueField, $labelField);
}
public function getSelectCountSql(){
$countSelect = parent::getSelectCountSql();
$countSelect->reset(Zend_Db_Select::GROUP);
return $countSelect;
}
}
코드가 너무 길어서 하나의 답변에 맞지 않습니다. 나머지는 따를 것이다.
2 부 .
app/code/local/Easylife/News/Model/Attribute.php
-기사 속성에 대한 모델
<?php
class Easylife_News_Model_Attribute
extends Mage_Eav_Model_Entity_Attribute {
const SCOPE_STORE = 0;
const SCOPE_GLOBAL = 1;
const SCOPE_WEBSITE = 2;
const MODULE_NAME = 'Easylife_News';
const ENTITY = 'easylife_news_eav_attribute';
protected $_eventPrefix = 'easylife_news_entity_attribute';
protected $_eventObject = 'attribute';
static protected $_labels = null;
protected function _construct(){
$this->_init('easylife_news/attribute');
}
protected function _beforeSave(){
$this->setData('modulePrefix', self::MODULE_NAME);
if (isset($this->_origData['is_global'])) {
if (!isset($this->_data['is_global'])) {
$this->_data['is_global'] = self::SCOPE_GLOBAL;
}
}
if ($this->getFrontendInput() == 'textarea') {
if ($this->getIsWysiwygEnabled()) {
$this->setIsHtmlAllowedOnFront(1);
}
}
return parent::_beforeSave();
}
protected function _afterSave(){
Mage::getSingleton('eav/config')->clear();
return parent::_afterSave();
}
public function getIsGlobal(){
return $this->_getData('is_global');
}
public function isScopeGlobal(){
return $this->getIsGlobal() == self::SCOPE_GLOBAL;
}
public function isScopeWebsite(){
return $this->getIsGlobal() == self::SCOPE_WEBSITE;
}
public function isScopeStore(){
return !$this->isScopeGlobal() && !$this->isScopeWebsite();
}
public function getStoreId(){
$dataObject = $this->getDataObject();
if ($dataObject) {
return $dataObject->getStoreId();
}
return $this->getData('store_id');
}
public function getSourceModel(){
$model = $this->getData('source_model');
if (empty($model)) {
if ($this->getBackendType() == 'int' && $this->getFrontendInput() == 'select') {
return $this->_getDefaultSourceModel();
}
}
return $model;
}
public function getFrontendLabel(){
return $this->_getData('frontend_label');
}
protected function _getLabelForStore(){
return $this->getFrontendLabel();
}
public static function initLabels($storeId = null){
if (is_null(self::$_labels)) {
if (is_null($storeId)) {
$storeId = Mage::app()->getStore()->getId();
}
$attributeLabels = array();
$attributes = Mage::getResourceSingleton('catalog/product')->getAttributesByCode();
foreach ($attributes as $attribute) {
if (strlen($attribute->getData('frontend_label')) > 0) {
$attributeLabels[] = $attribute->getData('frontend_label');
}
}
self::$_labels = Mage::app()->getTranslator()->getResource()->getTranslationArrayByStrings($attributeLabels, $storeId);
}
}
public function _getDefaultSourceModel(){
return 'eav/entity_attribute_source_table';
}
}
app/code/local/Easylife/News/Model/Resource/Attribute.php
-속성 자원 모델
<?php
class Easylife_News_Model_Resource_Attribute
extends Mage_Eav_Model_Resource_Entity_Attribute {
protected function _afterSave(Mage_Core_Model_Abstract $object){
$setup = Mage::getModel('eav/entity_setup', 'core_write');
$entityType = $object->getEntityTypeId();
$setId = $setup->getDefaultAttributeSetId($entityType);
$groupId = $setup->getDefaultAttributeGroupId($entityType);
$attributeId = $object->getId();
$sortOrder = $object->getPosition();
$setup->addAttributeToGroup($entityType, $setId, $groupId, $attributeId, $sortOrder);
return parent::_afterSave($object);
}
}
app/code/local/Easylife/News/Model/Resource/Eav/Attribute.php
-속성 EAV 자원 모델
<?php
class Easylife_News_Model_Resource_Eav_Attribute
extends Mage_Eav_Model_Entity_Attribute {
const MODULE_NAME = 'Easylife_News';
const ENTITY = 'easylife_news_eav_attribute';
protected $_eventPrefix = 'easylife_news_entity_attribute';
protected $_eventObject = 'attribute';
static protected $_labels = null;
protected function _construct() {
$this->_init('easylife_news/attribute');
}
public function isScopeStore() {
return $this->getIsGlobal() == Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE;
}
public function isScopeWebsite() {
return $this->getIsGlobal() == Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE;
}
public function isScopeGlobal() {
return (!$this->isScopeStore() && !$this->isScopeWebsite());
}
public function getBackendTypeByInput($type) {
switch ($type){
case 'file':
//intentional fallthrough
case 'image':
return 'varchar';
break;
default:
return parent::getBackendTypeByInput($type);
break;
}
}
protected function _beforeDelete(){
if (!$this->getIsUserDefined()){
throw new Mage_Core_Exception(Mage::helper('easylife_news')->__('This attribute is not deletable'));
}
return parent::_beforeDelete();
}
}
app/code/local/Easylife/News/Model/Resource/Article/Collection.php
-속성 수집 모델
<?php
class Easylife_News_Model_Resource_Article_Attribute_Collection
extends Mage_Eav_Model_Resource_Entity_Attribute_Collection {
protected function _initSelect() {
$this->getSelect()->from(array('main_table' => $this->getResource()->getMainTable()))
->where('main_table.entity_type_id=?', Mage::getModel('eav/entity')->setType('easylife_news_article')->getTypeId())
->join(
array('additional_table' => $this->getTable('easylife_news/eav_attribute')),
'additional_table.attribute_id=main_table.attribute_id'
);
return $this;
}
public function setEntityTypeFilter($typeId) {
return $this;
}
public function addVisibleFilter() {
return $this->addFieldToFilter('additional_table.is_visible', 1);
}
public function addEditableFilter() {
return $this->addFieldToFilter('additional_table.is_editable', 1);
}
}
app/code/local/Easylife/News/Model/Resource/Setup.php
-설정 자원 모델-엔티티 및 속성을 추가하는 데 사용됩니다.
<?php
class Easylife_News_Model_Resource_Setup
extends Mage_Catalog_Model_Resource_Setup {
public function getDefaultEntities(){
$entities = array();
$entities['easylife_news_article'] = array(
'entity_model' => 'easylife_news/article',
'attribute_model' => 'easylife_news/resource_eav_attribute',
'table' => 'easylife_news/article',
'additional_attribute_table' => 'easylife_news/eav_attribute',
'entity_attribute_collection' => 'easylife_news/article_attribute_collection',
'attributes' => array(
'title' => array(
'group' => 'General',
'type' => 'varchar',
'backend' => '',
'frontend' => '',
'label' => 'Title',
'input' => 'text',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '1',
'user_defined' => false,
'default' => '',
'unique' => false,
'position' => '10',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'short_description' => array(
'group' => 'General',
'type' => 'text',
'backend' => '',
'frontend' => '',
'label' => 'Short description',
'input' => 'textarea',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '1',
'user_defined' => true,
'default' => '',
'unique' => false,
'position' => '20',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'description' => array(
'group' => 'General',
'type' => 'text',
'backend' => '',
'frontend' => '',
'label' => 'Description',
'input' => 'textarea',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '1',
'user_defined' => true,
'default' => '',
'unique' => false,
'position' => '30',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '1',
),
'publish_date' => array(
'group' => 'General',
'type' => 'datetime',
'backend' => 'eav/entity_attribute_backend_datetime',
'frontend' => '',
'label' => 'Publish Date',
'input' => 'date',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'required' => '1',
'user_defined' => true,
'default' => '',
'unique' => false,
'position' => '40',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'status' => array(
'group' => 'General',
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Enabled',
'input' => 'select',
'source' => 'eav/entity_attribute_source_boolean',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '',
'user_defined' => false,
'default' => '',
'unique' => false,
'position' => '50',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'url_key' => array(
'group' => 'General',
'type' => 'varchar',
'backend' => 'easylife_news/article_attribute_backend_urlkey',
'frontend' => '',
'label' => 'URL key',
'input' => 'text',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '',
'user_defined' => false,
'default' => '',
'unique' => false,
'position' => '60',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'in_rss' => array(
'group' => 'General',
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'In RSS',
'input' => 'select',
'source' => 'eav/entity_attribute_source_boolean',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '',
'user_defined' => false,
'default' => '',
'unique' => false,
'position' => '70',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'meta_title' => array(
'group' => 'General',
'type' => 'varchar',
'backend' => '',
'frontend' => '',
'label' => 'Meta title',
'input' => 'text',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '',
'user_defined' => false,
'default' => '',
'unique' => false,
'position' => '80',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'meta_keywords' => array(
'group' => 'General',
'type' => 'text',
'backend' => '',
'frontend' => '',
'label' => 'Meta keywords',
'input' => 'textarea',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '',
'user_defined' => false,
'default' => '',
'unique' => false,
'position' => '90',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
'meta_description' => array(
'group' => 'General',
'type' => 'text',
'backend' => '',
'frontend' => '',
'label' => 'Meta description',
'input' => 'textarea',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'required' => '',
'user_defined' => false,
'default' => '',
'unique' => false,
'position' => '100',
'note' => '',
'visible' => '1',
'wysiwyg_enabled'=> '0',
),
)
);
return $entities;
}
}
app/code/local/Easylife/News/Model/Article/Attribute/Backend/File.php
-파일 속성을 추가하기로 결정한 경우 파일 속성의 백엔드
<?php
class Easylife_News_Model_Article_Attribute_Backend_File
extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract {
public function afterSave($object){
$value = $object->getData($this->getAttribute()->getName());
if (is_array($value) && !empty($value['delete'])) {
$object->setData($this->getAttribute()->getName(), '');
$this->getAttribute()->getEntity()
->saveAttribute($object, $this->getAttribute()->getName());
return;
}
$path = Mage::helper('easylife_news/article')->getFileBaseDir();
try {
$uploader = new Varien_File_Uploader($this->getAttribute()->getName());
//set allowed file extensions if you need
//$uploader->setAllowedExtensions(array('mp4', 'mov', 'f4v', 'flv', '3gp', '3g2', 'mp3', 'aac', 'm4a', 'swf'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$result = $uploader->save($path);
$object->setData($this->getAttribute()->getName(), $result['file']);
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
} catch (Exception $e) {
if ($e->getCode() != 666){
//throw $e;
}
return;
}
}
}
app/code/local/Easylife/News/Model/Article/Attribute/Backend/Image.php
-이미지 속성을 추가하기로 결정한 경우 이미지 속성의 백엔드
<?php
class Easylife_News_Model_Article_Attribute_Backend_Image
extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract {
public function afterSave($object){
$value = $object->getData($this->getAttribute()->getName());
if (is_array($value) && !empty($value['delete'])) {
$object->setData($this->getAttribute()->getName(), '');
$this->getAttribute()->getEntity()
->saveAttribute($object, $this->getAttribute()->getName());
return;
}
$path = Mage::helper('easylife_news/article_image')->getImageBaseDir();
try {
$uploader = new Varien_File_Uploader($this->getAttribute()->getName());
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$result = $uploader->save($path);
$object->setData($this->getAttribute()->getName(), $result['file']);
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
} catch (Exception $e) {
if ($e->getCode() != 666){
//throw $e;
}
return;
}
}
}
app/code/local/Easylife/News/Model/Article/Attribute/Backend/Urlkey.php
-URL 키 속성의 백엔드
<?php
class Easylife_News_Model_Article_Attribute_Backend_Urlkey
extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract {
public function beforeSave($object) {
$attributeName = $this->getAttribute()->getName();
$urlKey = $object->getData($attributeName);
if ($urlKey == '') {
$urlKey = $object->getTitle();
}
$urlKey = $this->formatUrlKey($urlKey);
$validKey = false;
while (!$validKey) {
$entityId = Mage::getResourceModel('easylife_news/article')->checkUrlKey($urlKey, $object->getStoreId(), false);
if ($entityId == $object->getId() || empty($entityId)) {
$validKey = true;
}
else {
$parts = explode('-', $urlKey);
$last = $parts[count($parts) - 1];
if (!is_numeric($last)){
$urlKey = $urlKey.'-1';
}
else {
$suffix = '-'.($last + 1);
unset($parts[count($parts) - 1]);
$urlKey = implode('-', $parts).$suffix;
}
}
}
$object->setData($attributeName, $urlKey);
return $this;
}
public function formatUrlKey($str) {
$urlKey = preg_replace('#[^0-9a-z]+#i', '-', Mage::helper('catalog/product_url')->format($str));
$urlKey = strtolower($urlKey);
$urlKey = trim($urlKey, '-');
return $urlKey;
}
}
app/code/local/Easylife/News/Model/Adminhtml/Search/Article.php
-관리자 글로벌 검색을 처리하는 모델
<?php
class Easylife_News_Model_Adminhtml_Search_Article
extends Varien_Object {
public function load(){
$arr = array();
if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) {
$this->setResults($arr);
return $this;
}
$collection = Mage::getResourceModel('easylife_news/article_collection')
->addAttributeToFilter('title', array('like' => $this->getQuery().'%'))
->setCurPage($this->getStart())
->setPageSize($this->getLimit())
->load();
foreach ($collection->getItems() as $article) {
$arr[] = array(
'id'=> 'article/1/'.$article->getId(),
'type' => Mage::helper('easylife_news')->__('Article'),
'name' => $article->getTitle(),
'description' => $article->getTitle(),
'url' => Mage::helper('adminhtml')->getUrl('*/news_article/edit', array('id'=>$article->getId())),
);
}
$this->setResults($arr);
return $this;
}
}
모델이 완성되었습니다. 블록으로 넘어 갑시다 .
app/code/local/Easylife/News/Block/Rss.php
-일반 RSS 블록
<?php
class Easylife_News_Block_Rss
extends Mage_Core_Block_Template {
protected $_feeds = array();
public function addFeed($label, $url, $prepare = false) {
$link = ($prepare ? $this->getUrl($url) : $url);
$feed = new Varien_Object();
$feed->setLabel($label);
$feed->setUrl($link);
$this->_feeds[$link] = $feed;
return $this;
}
public function getFeeds() {
return $this->_feeds;
}
}
app/code/local/Easylife/News/Block/Adminhtml/Article.php
-주요 기사 블록
<?php
class Easylife_News_Block_Adminhtml_Article
extends Mage_Adminhtml_Block_Widget_Grid_Container {
public function __construct(){
$this->_controller = 'adminhtml_article';
$this->_blockGroup = 'easylife_news';
parent::__construct();
$this->_headerText = Mage::helper('easylife_news')->__('Article');
$this->_updateButton('add', 'label', Mage::helper('easylife_news')->__('Add Article'));
$this->setTemplate('easylife_news/grid.phtml');
}
}
app/code/local/Easylife/News/Block/Adminhtml/Article/Edit.php
-관리자 편집 양식
<?php
class Easylife_News_Block_Adminhtml_Article_Edit
extends Mage_Adminhtml_Block_Widget_Form_Container {
public function __construct(){
parent::__construct();
$this->_blockGroup = 'easylife_news';
$this->_controller = 'adminhtml_article';
$this->_updateButton('save', 'label', Mage::helper('easylife_news')->__('Save Article'));
$this->_updateButton('delete', 'label', Mage::helper('easylife_news')->__('Delete Article'));
$this->_addButton('saveandcontinue', array(
'label' => Mage::helper('easylife_news')->__('Save And Continue Edit'),
'onclick' => 'saveAndContinueEdit()',
'class' => 'save',
), -100);
$this->_formScripts[] = "
function saveAndContinueEdit(){
editForm.submit($('edit_form').action+'back/edit/');
}
";
}
public function getHeaderText(){
if( Mage::registry('current_article') && Mage::registry('current_article')->getId() ) {
return Mage::helper('easylife_news')->__("Edit Article '%s'", $this->escapeHtml(Mage::registry('current_article')->getTitle()));
}
else {
return Mage::helper('easylife_news')->__('Add Article');
}
}
}
3. 부분이있을 것 같습니다 .....
3 부
app/code/local/Easylife/News/Block/Adminhtml/Article/Grid.php
.-관리 그리드
<?php
class Easylife_News_Block_Adminhtml_Article_Grid
extends Mage_Adminhtml_Block_Widget_Grid {
public function __construct(){
parent::__construct();
$this->setId('articleGrid');
$this->setDefaultSort('entity_id');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
protected function _prepareCollection(){
$collection = Mage::getModel('easylife_news/article')->getCollection()
->addAttributeToSelect('publish_date')
->addAttributeToSelect('status')
->addAttributeToSelect('url_key');
$adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
$store = $this->_getStore();
$collection->joinAttribute('title', 'easylife_news_article/title', 'entity_id', null, 'inner', $adminStore);
if ($store->getId()) {
$collection->joinAttribute('easylife_news_article_title', 'easylife_news_article/title', 'entity_id', null, 'inner', $store->getId());
}
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns(){
$this->addColumn('entity_id', array(
'header' => Mage::helper('easylife_news')->__('Id'),
'index' => 'entity_id',
'type' => 'number'
));
$this->addColumn('title', array(
'header' => Mage::helper('easylife_news')->__('Title'),
'align' => 'left',
'index' => 'title',
));
if ($this->_getStore()->getId()){
$this->addColumn('easylife_news_article_title', array(
'header' => Mage::helper('easylife_news')->__('Title in %s', $this->_getStore()->getName()),
'align' => 'left',
'index' => 'easylife_news_article_title',
));
}
$this->addColumn('status', array(
'header' => Mage::helper('easylife_news')->__('Status'),
'index' => 'status',
'type' => 'options',
'options' => array(
'1' => Mage::helper('easylife_news')->__('Enabled'),
'0' => Mage::helper('easylife_news')->__('Disabled'),
)
));
$this->addColumn('publish_date', array(
'header'=> Mage::helper('easylife_news')->__('Publish Date'),
'index' => 'publish_date',
'type'=> 'date',
));
$this->addColumn('url_key', array(
'header' => Mage::helper('easylife_news')->__('URL key'),
'index' => 'url_key',
));
$this->addColumn('created_at', array(
'header' => Mage::helper('easylife_news')->__('Created at'),
'index' => 'created_at',
'width' => '120px',
'type' => 'datetime',
));
$this->addColumn('updated_at', array(
'header' => Mage::helper('easylife_news')->__('Updated at'),
'index' => 'updated_at',
'width' => '120px',
'type' => 'datetime',
));
$this->addColumn('action',
array(
'header'=> Mage::helper('easylife_news')->__('Action'),
'width' => '100',
'type' => 'action',
'getter'=> 'getId',
'actions' => array(
array(
'caption' => Mage::helper('easylife_news')->__('Edit'),
'url' => array('base'=> '*/*/edit'),
'field' => 'id'
)
),
'filter'=> false,
'is_system' => true,
'sortable' => false,
));
$this->addExportType('*/*/exportCsv', Mage::helper('easylife_news')->__('CSV'));
$this->addExportType('*/*/exportExcel', Mage::helper('easylife_news')->__('Excel'));
$this->addExportType('*/*/exportXml', Mage::helper('easylife_news')->__('XML'));
return parent::_prepareColumns();
}
protected function _getStore(){
$storeId = (int) $this->getRequest()->getParam('store', 0);
return Mage::app()->getStore($storeId);
}
protected function _prepareMassaction(){
$this->setMassactionIdField('entity_id');
$this->getMassactionBlock()->setFormFieldName('article');
$this->getMassactionBlock()->addItem('delete', array(
'label'=> Mage::helper('easylife_news')->__('Delete'),
'url' => $this->getUrl('*/*/massDelete'),
'confirm' => Mage::helper('easylife_news')->__('Are you sure?')
));
$this->getMassactionBlock()->addItem('status', array(
'label'=> Mage::helper('easylife_news')->__('Change status'),
'url' => $this->getUrl('*/*/massStatus', array('_current'=>true)),
'additional' => array(
'status' => array(
'name' => 'status',
'type' => 'select',
'class' => 'required-entry',
'label' => Mage::helper('easylife_news')->__('Status'),
'values' => array(
'1' => Mage::helper('easylife_news')->__('Enabled'),
'0' => Mage::helper('easylife_news')->__('Disabled'),
)
)
)
));
return $this;
}
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/Easylife/News/Block/Adminhtml/Article/Edit/Tabs.php
-추가 / 편집 양식의 탭
<?php
class Easylife_News_Block_Adminhtml_Article_Edit_Tabs
extends Mage_Adminhtml_Block_Widget_Tabs {
public function __construct() {
parent::__construct();
$this->setId('article_info_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(Mage::helper('easylife_news')->__('Article Information'));
}
protected function _prepareLayout(){
$article = $this->getArticle();
$entity = Mage::getModel('eav/entity_type')->load('easylife_news_article', 'entity_type_code');
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($entity->getEntityTypeId());
$attributes->addFieldToFilter('attribute_code', array('nin'=>array('meta_title', 'meta_description', 'meta_keywords')));
$attributes->getSelect()->order('additional_table.position', 'ASC');
$this->addTab('info', array(
'label' => Mage::helper('easylife_news')->__('Article Information'),
'content' => $this->getLayout()->createBlock('easylife_news/adminhtml_article_edit_tab_attributes')
->setAttributes($attributes)
->toHtml(),
));
$seoAttributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($entity->getEntityTypeId())
->addFieldToFilter('attribute_code', array('in'=>array('meta_title', 'meta_description', 'meta_keywords')));
$seoAttributes->getSelect()->order('additional_table.position', 'ASC');
$this->addTab('meta', array(
'label' => Mage::helper('easylife_news')->__('Meta'),
'title' => Mage::helper('easylife_news')->__('Meta'),
'content' => $this->getLayout()->createBlock('easylife_news/adminhtml_article_edit_tab_attributes')
->setAttributes($seoAttributes)
->toHtml(),
));
return parent::_beforeToHtml();
}
public function getArticle(){
return Mage::registry('current_article');
}
}
app/code/local/Easylife/News/Block/Adminhtml/Article/Edit/Form.php
-양식 컨테이너
<?php
class Easylife_News_Block_Adminhtml_Article_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'), 'store' => $this->getRequest()->getParam('store'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
app/code/local/Easylife/News/Block/Adminhtml/Article/Edit/Tab/Attribtues.php
-탭에 포함 된 속성
<?php
class Easylife_News_Block_Adminhtml_Article_Edit_Tab_Attributes
extends Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm() {
$form = new Varien_Data_Form();
$form->setDataObject(Mage::registry('current_article'));
$fieldset = $form->addFieldset('info',
array(
'legend'=>Mage::helper('easylife_news')->__('Article Information'),
'class'=>'fieldset-wide',
)
);
$attributes = $this->getAttributes();
foreach ($attributes as $attribute){
$attribute->setEntity(Mage::getResourceModel('easylife_news/article'));
}
$this->_setFieldset($attributes, $fieldset, array());
$formValues = Mage::registry('current_article')->getData();
$form->addValues($formValues);
$form->setFieldNameSuffix('article');
$this->setForm($form);
}
protected function _prepareLayout() {
Varien_Data_Form::setElementRenderer(
$this->getLayout()->createBlock('adminhtml/widget_form_renderer_element')
);
Varien_Data_Form::setFieldsetRenderer(
$this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset')
);
Varien_Data_Form::setFieldsetElementRenderer(
$this->getLayout()->createBlock('easylife_news/adminhtml_news_renderer_fieldset_element')
);
}
protected function _getAdditionalElementTypes(){
return array(
'file' => Mage::getConfig()->getBlockClassName('easylife_news/adminhtml_article_helper_file'),
'image' => Mage::getConfig()->getBlockClassName('easylife_news/adminhtml_article_helper_image'),
'textarea' => Mage::getConfig()->getBlockClassName('adminhtml/catalog_helper_form_wysiwyg')
);
}
public function getArticle() {
return Mage::registry('current_article');
}
}
app/code/local/Easylfe/News/Block/Adminhtml/Article/Helper/File.php
-파일 요소를 렌더링하기위한 블록 도우미.
<?php
class Easylife_News_Block_Adminhtml_Article_Helper_File
extends Varien_Data_Form_Element_Abstract {
public function __construct($data){
parent::__construct($data);
$this->setType('file');
}
public function getElementHtml(){
$html = '';
$this->addClass('input-file');
$html.= parent::getElementHtml();
if ($this->getValue()) {
$url = $this->_getUrl();
if( !preg_match("/^http\:\/\/|https\:\/\//", $url) ) {
$url = Mage::helper('easylife_news/article')->getFileBaseUrl() . $url;
}
$html .= '<br /><a href="'.$url.'">'.$this->_getUrl().'</a> ';
}
$html.= $this->_getDeleteCheckbox();
return $html;
}
protected function _getDeleteCheckbox(){
$html = '';
if ($this->getValue()) {
$label = Mage::helper('easylife_news')->__('Delete File');
$html .= '<span class="delete-image">';
$html .= '<input type="checkbox" name="'.parent::getName().'[delete]" value="1" class="checkbox" id="'.$this->getHtmlId().'_delete"'.($this->getDisabled() ? ' disabled="disabled"': '').'/>';
$html .= '<label for="'.$this->getHtmlId().'_delete"'.($this->getDisabled() ? ' class="disabled"' : '').'> '.$label.'</label>';
$html .= $this->_getHiddenInput();
$html .= '</span>';
}
return $html;
}
protected function _getHiddenInput(){
return '<input type="hidden" name="'.parent::getName().'[value]" value="'.$this->getValue().'" />';
}
protected function _getUrl(){
return $this->getValue();
}
public function getName(){
return $this->getData('name');
}
}
app/code/local/Easylfe/News/Block/Adminhtml/Article/Helper/Image.php
-이미지 요소를 렌더링하기위한 블록 도우미.
<?php
class Easylife_News_Block_Adminhtml_Article_Helper_Image
extends Varien_Data_Form_Element_Image {
protected function _getUrl(){
$url = false;
if ($this->getValue()) {
$url = Mage::helper('easylife_news/article_image')->getImageBaseUrl().$this->getValue();
}
return $url;
}
}
app/code/local/Easylife/News/Block/Adminhtml/Attribute.php
-속성 관리를위한 메인 블록
<?php
class Easylife_News_Block_Adminhtml_Article_Attribute
extends Mage_Adminhtml_Block_Widget_Grid_Container {
public function __construct(){
$this->_controller = 'adminhtml_article_attribute';
$this->_blockGroup = 'easylife_news';
$this->_headerText = Mage::helper('easylife_news')->__('Manage Article Attributes');
parent::__construct();
$this->_updateButton('add', 'label', Mage::helper('easylife_news')->__('Add New Article Attribute'));
}
}
app/code/local/Easylife/News/Block/Adminhtml/Attribute/Grid.php
-속성 그리드 블록
<?php
class Easylife_News_Block_Adminhtml_Article_Attribute_Grid
extends Mage_Eav_Block_Adminhtml_Attribute_Grid_Abstract {
protected function _prepareCollection(){
$collection = Mage::getResourceModel('easylife_news/article_attribute_collection')
->addVisibleFilter();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns() {
parent::_prepareColumns();
$this->addColumnAfter('is_global', array(
'header'=>Mage::helper('easylife_news')->__('Scope'),
'sortable'=>true,
'index'=>'is_global',
'type' => 'options',
'options' => array(
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE =>Mage::helper('easylife_news')->__('Store View'),
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE =>Mage::helper('easylife_news')->__('Website'),
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL =>Mage::helper('easylife_news')->__('Global'),
),
'align' => 'center',
), 'is_user_defined');
return $this;
}
}
app/code/local/Easylife/News/Block/Adminhtml/Attribute/Edit.php
-속성 편집 양식
<?php
class Easylife_News_Block_Adminhtml_Article_Attribute_Edit
extends Mage_Adminhtml_Block_Widget_Form_Container {
public function __construct() {
$this->_objectId = 'attribute_id';
$this->_controller = 'adminhtml_article_attribute';
$this->_blockGroup = 'easylife_news';
parent::__construct();
$this->_addButton(
'save_and_edit_button',
array(
'label' => Mage::helper('easylife_news')->__('Save and Continue Edit'),
'onclick' => 'saveAndContinueEdit()',
'class' => 'save'
),
100
);
$this->_updateButton('save', 'label', Mage::helper('easylife_news')->__('Save Article Attribute'));
$this->_updateButton('save', 'onclick', 'saveAttribute()');
if (!Mage::registry('entity_attribute')->getIsUserDefined()) {
$this->_removeButton('delete');
} else {
$this->_updateButton('delete', 'label', Mage::helper('easylife_news')->__('Delete Article Attribute'));
}
}
public function getHeaderText(){
if (Mage::registry('entity_attribute')->getId()) {
$frontendLabel = Mage::registry('entity_attribute')->getFrontendLabel();
if (is_array($frontendLabel)) {
$frontendLabel = $frontendLabel[0];
}
return Mage::helper('easylife_news')->__('Edit Article Attribute "%s"', $this->htmlEscape($frontendLabel));
}
else {
return Mage::helper('easylife_news')->__('New Article Attribute');
}
}
public function getValidationUrl(){
return $this->getUrl('*/*/validate', array('_current'=>true));
}
public function getSaveUrl(){
return $this->getUrl('*/'.$this->_controller.'/save', array('_current'=>true, 'back'=>null));
}
}
app/code/local/Easylife/News/Block/Adminhtml/Attribute/Edit/Tabs.php
-속성 편집 탭
<?php
class Easylife_News_Block_Adminhtml_Article_Attribute_Edit_Tabs
extends Mage_Adminhtml_Block_Widget_Tabs {
public function __construct() {
parent::__construct();
$this->setId('article_attribute_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(Mage::helper('easylife_news')->__('Attribute Information'));
}
protected function _beforeToHtml() {
$this->addTab('main', array(
'label' => Mage::helper('easylife_news')->__('Properties'),
'title' => Mage::helper('easylife_news')->__('Properties'),
'content' => $this->getLayout()->createBlock('easylife_news/adminhtml_article_attribute_edit_tab_main')->toHtml(),
'active' => true
));
$this->addTab('labels', array(
'label' => Mage::helper('easylife_news')->__('Manage Label / Options'),
'title' => Mage::helper('easylife_news')->__('Manage Label / Options'),
'content' => $this->getLayout()->createBlock('easylife_news/adminhtml_article_attribute_edit_tab_options')->toHtml(),
));
return parent::_beforeToHtml();
}
}
app/code/local/Easylife/News/Block/Adminhtml/Attribute/Edit/Form.php
-속성 편집 폼 컨테이너
<?php
class Easylife_News_Block_Adminhtml_Article_Attribute_Edit_Form
extends Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm() {
$form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => $this->getUrl('adminhtml/news_article_attribute/save'), 'method' => 'post'));
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
app/code/local/Easylife/News/Block/Adminhtml/Attribute/Edit/Tab/Main.php
-속성 편집 기본 탭 :
<?php
class Easylife_News_Block_Adminhtml_Article_Attribute_Edit_Tab_Main
extends Mage_Eav_Block_Adminhtml_Attribute_Edit_Main_Abstract {
protected function _prepareForm(){
parent::_prepareForm();
$attributeObject = $this->getAttributeObject();
$form = $this->getForm();
$fieldset = $form->getElement('base_fieldset');
$frontendInputElm = $form->getElement('frontend_input');
$additionalTypes = array(
array(
'value' => 'image',
'label' => Mage::helper('easylife_news')->__('Image')
),
array(
'value' => 'file',
'label' => Mage::helper('easylife_news')->__('File')
)
);
$response = new Varien_Object();
$response->setTypes(array());
Mage::dispatchEvent('adminhtml_article_attribute_types', array('response'=>$response));
$_disabledTypes = array();
$_hiddenFields = array();
foreach ($response->getTypes() as $type) {
$additionalTypes[] = $type;
if (isset($type['hide_fields'])) {
$_hiddenFields[$type['value']] = $type['hide_fields'];
}
if (isset($type['disabled_types'])) {
$_disabledTypes[$type['value']] = $type['disabled_types'];
}
}
Mage::register('attribute_type_hidden_fields', $_hiddenFields);
Mage::register('attribute_type_disabled_types', $_disabledTypes);
$frontendInputValues = array_merge($frontendInputElm->getValues(), $additionalTypes);
$frontendInputElm->setValues($frontendInputValues);
$yesnoSource = Mage::getModel('adminhtml/system_config_source_yesno')->toOptionArray();
$scopes = array(
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE =>Mage::helper('easylife_news')->__('Store View'),
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE =>Mage::helper('easylife_news')->__('Website'),
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL =>Mage::helper('easylife_news')->__('Global'),
);
$fieldset->addField('is_global', 'select', array(
'name' => 'is_global',
'label' => Mage::helper('easylife_news')->__('Scope'),
'title' => Mage::helper('easylife_news')->__('Scope'),
'note' => Mage::helper('easylife_news')->__('Declare attribute value saving scope'),
'values'=> $scopes
), 'attribute_code');
$fieldset->addField('position', 'text', array(
'name' => 'position',
'label' => Mage::helper('easylife_news')->__('Position'),
'title' => Mage::helper('easylife_news')->__('Position'),
'note' => Mage::helper('easylife_news')->__('Position in the admin form'),
), 'is_global');
$fieldset->addField('note', 'textarea', array(
'name' => 'note',
'label' => Mage::helper('easylife_news')->__('Note'),
'title' => Mage::helper('easylife_news')->__('Note'),
'note' => Mage::helper('easylife_news')->__('Text to appear below the input.'),
), 'position');
$fieldset->removeField('default_value_text');
$fieldset->removeField('default_value_yesno');
$fieldset->removeField('default_value_date');
$fieldset->removeField('default_value_textarea');
$fieldset->removeField('is_unique');
// frontend properties fieldset
$fieldset = $form->addFieldset('front_fieldset', array('legend'=>Mage::helper('easylife_news')->__('Frontend Properties')));
$fieldset->addField('is_wysiwyg_enabled', 'select', array(
'name' => 'is_wysiwyg_enabled',
'label' => Mage::helper('easylife_news')->__('Enable WYSIWYG'),
'title' => Mage::helper('easylife_news')->__('Enable WYSIWYG'),
'values' => $yesnoSource,
));
Mage::dispatchEvent('easylife_news_adminhtml_article_attribute_edit_prepare_form', array(
'form' => $form,
'attribute' => $attributeObject
));
return $this;
}
}
app/code/local/Easylife/News/Block/Adminhtml/Attribute/Edit/Tab/Options.php
-속성 옵션 렌더링을위한 탭
<?php
class Easylife_News_Block_Adminhtml_Article_Attribute_Edit_Tab_Options
extends Mage_Eav_Block_Adminhtml_Attribute_Edit_Options_Abstract {
}
app/code/local/Easylife/News/Block/Adminhtml/News/Helper/Form/Wysiwyg/Content.php
-WYSIWYG 요소의 도우미 블록
<?php
class Easylife_News_Block_Adminhtml_News_Helper_Form_Wysiwyg_Content
extends Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm(){
$form = new Varien_Data_Form(array('id' => 'wysiwyg_edit_form', 'action' => $this->getData('action'), 'method' => 'post'));
$config['document_base_url'] = $this->getData('store_media_url');
$config['store_id'] = $this->getData('store_id');
$config['add_variables'] = false;
$config['add_widgets'] = false;
$config['add_directives'] = true;
$config['use_container'] = true;
$config['container_class'] = 'hor-scroll';
$editorConfig = Mage::getSingleton('cms/wysiwyg_config')->getConfig($config);
$editorConfig->setData('files_browser_window_url', Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/cms_wysiwyg_images/index'));
$form->addField($this->getData('editor_element_id'), 'editor', array(
'name' => 'content',
'style' => 'width:725px;height:460px',
'required' => true,
'force_load' => true,
'config' => $editorConfig
));
$this->setForm($form);
return parent::_prepareForm();
}
}
이제 파트 4를 찾으십시오.
Easylife_News_Block_Adminhtml_Article_Edit_Tab_Attributes
이 있고 올바른 장소에 있는지 확인하십시오 .
<blocks>
config.xml 파일에 태그가 있는지 확인하십시오 . 어떤 이유로 메소드 호출 getBlock('easylife_news/adminhtml_article_edit_tab_attributes')
은 false를 리턴합니다. 이는 블록이 존재하지 않거나 인스턴스화 할 수 없음을 의미합니다. 이와 같은 문제를 피하려면이 도구 github.com/tzyganu/UMC1.9 를 사용하여 eav 엔티티 모듈을 작성 하는 것이 좋습니다 .
4 부
app/code/local/Easylife/News/Block/Adminhtml/News/Renderer/Fieldset/Element.php
-fieldset 요소 렌더러.
<?php
class Easylife_News_Block_Adminhtml_News_Renderer_Fieldset_Element
extends Mage_Adminhtml_Block_Widget_Form_Renderer_Fieldset_Element {
protected function _construct() {
$this->setTemplate('easylife_news/form/renderer/fieldset/element.phtml');
}
public function getDataObject() {
return $this->getElement()->getForm()->getDataObject();
}
public function getAttribute() {
return $this->getElement()->getEntityAttribute();
}
public function getAttributeCode(){
return $this->getAttribute()->getAttributeCode();
}
public function canDisplayUseDefault(){
if ($attribute = $this->getAttribute()) {
if (!$this->isScopeGlobal($attribute)
&& $this->getDataObject()
&& $this->getDataObject()->getId()
&& $this->getDataObject()->getStoreId()) {
return true;
}
}
return false;
}
public function usedDefault(){
$defaultValue = $this->getDataObject()->getAttributeDefaultValue($this->getAttribute()->getAttributeCode());
return !$defaultValue;
}
public function checkFieldDisable(){
if ($this->canDisplayUseDefault() && $this->usedDefault()) {
$this->getElement()->setDisabled(true);
}
return $this;
}
public function getScopeLabel(){
$html = '';
$attribute = $this->getElement()->getEntityAttribute();
if (!$attribute || Mage::app()->isSingleStoreMode()) {
return $html;
}
if ($this->isScopeGlobal($attribute)) {
$html.= Mage::helper('easylife_news')->__('[GLOBAL]');
}
elseif ($this->isScopeWebsite($attribute)) {
$html.= Mage::helper('easylife_news')->__('[WEBSITE]');
}
elseif ($this->isScopeStore($attribute)) {
$html.= Mage::helper('easylife_news')->__('[STORE VIEW]');
}
return $html;
}
public function getElementLabelHtml(){
return $this->getElement()->getLabelHtml();
}
public function getElementHtml(){
return $this->getElement()->getElementHtml();
}
public function isScopeGlobal($attribute){
return $attribute->getIsGlobal() == 1;
}
public function isScopeWebsite($attribute){
return $attribute->getIsGlobal() == 2;
}
public function isScopeStore($attribute){
return !$this->isScopeGlobal($attribute) && !$this->isScopeWebsite($attribute);
}
}
app/code/local/Easylife/News/Block/Article/List.php
-기사 프론트 엔드 목록 블록.
<?php
class Easylife_News_Block_Article_List
extends Mage_Core_Block_Template {
public function __construct(){
parent::__construct();
$articles = Mage::getResourceModel('easylife_news/article_collection')
->setStoreId(Mage::app()->getStore()->getId())
->addAttributeToSelect('*')
->addAttributeToFilter('status', 1);
$articles->setOrder('title', 'asc');
$this->setArticles($articles);
}
protected function _prepareLayout(){
parent::_prepareLayout();
$pager = $this->getLayout()->createBlock('page/html_pager', 'easylife_news.article.html.pager')
->setCollection($this->getArticles());
$this->setChild('pager', $pager);
$this->getArticles()->load();
return $this;
}
public function getPagerHtml(){
return $this->getChildHtml('pager');
}
}
app/code/local/Easylife/News/Block/Article/View.php
-기사 프론트 엔드 뷰 블록.
<?php
class Easylife_News_Block_Article_View
extends Mage_Core_Block_Template {
public function getCurrentArticle(){
return Mage::registry('current_article');
}
}
app/code/local/Easylife/News/Block/Article/Rss.php
-기사 프론트 엔드 RSS 블록.
<?php
class Easylife_News_Block_Article_Rss
extends Mage_Rss_Block_Abstract {
const CACHE_TAG = 'block_html_news_article_rss';
protected function _construct(){
$this->setCacheTags(array(self::CACHE_TAG));
/*
* setting cache to save the rss for 10 minutes
*/
$this->setCacheKey('easylife_news_article_rss');
$this->setCacheLifetime(600);
}
protected function _toHtml(){
$url = Mage::helper('easylife_news/article')->getArticlesUrl();
$title = Mage::helper('easylife_news')->__('Articles');
$rssObj = Mage::getModel('rss/rss');
$data = array(
'title' => $title,
'description' => $title,
'link'=> $url,
'charset' => 'UTF-8',
);
$rssObj->_addHeader($data);
$collection = Mage::getModel('easylife_news/article')->getCollection()
->addFieldToFilter('status', 1)
->addAttributeToSelect('*')
->addAttributeToFilter('in_rss', 1)
->setOrder('created_at');
$collection->load();
foreach ($collection as $item){
$description = '<p>';
$description .= '<div>'.Mage::helper('easylife_news')->__('Title').': '.$item->getTitle().'</div>';
$description .= '<div>'.Mage::helper('easylife_news')->__('Short description').': '.$item->getShortDescription().'</div>';
$description .= '<div>'.Mage::helper('easylife_news')->__('Description').': '.$item->getDescription().'</div>';
$description .= '<div>'.Mage::helper('easylife_news')->__('Publish Date').': '.Mage::helper('core')->formatDate($item->getPublishDate(), 'full').'</div>';
$description .= '</p>';
$data = array(
'title'=>$item->getTitle(),
'link'=>$item->getArticleUrl(),
'description' => $description
);
$rssObj->_addEntry($data);
}
return $rssObj->createRssXml();
}
}
이제 URL 용 라우터 가 다시 작성됩니다.
app/code/local/Easylife/News/Controller/Router.php
-라우터
<?php
class Easylife_News_Controller_Router
extends Mage_Core_Controller_Varien_Router_Abstract {
public function initControllerRouters($observer){
$front = $observer->getEvent()->getFront();
$front->addRouter('easylife_news', $this);
return $this;
}
public function match(Zend_Controller_Request_Http $request){
if (!Mage::isInstalled()) {
Mage::app()->getFrontController()->getResponse()
->setRedirect(Mage::getUrl('install'))
->sendResponse();
exit;
}
$urlKey = trim($request->getPathInfo(), '/');
$check = array(); //you can add here multiple entities
$check['article'] = new Varien_Object(array(
'prefix' => Mage::getStoreConfig('easylife_news/article/url_prefix'),
'suffix' => Mage::getStoreConfig('easylife_news/article/url_suffix'),
'model' =>'easylife_news/article',
'controller' => 'article',
'action' => 'view',
'param' => 'id',
));
foreach ($check as $key=>$settings) {
if ($settings['prefix']){
$parts = explode('/', $urlKey);
if ($parts[0] != $settings['prefix'] || count($parts) != 2){
continue;
}
$urlKey = $parts[1];
}
if ($settings['suffix']){
$urlKey = substr($urlKey, 0 , -strlen($settings['suffix']) - 1);
}
$model = Mage::getModel($settings->getModel());
$id = $model->checkUrlKey($urlKey, Mage::app()->getStore()->getId());
if ($id){
if ($settings->getCheckPath() && !$model->load($id)->getStatusPath()) {
continue;
}
$request->setModuleName('news')
->setControllerName($settings->getController())
->setActionName($settings->getAction())
->setParam($settings->getParam(), $id);
$request->setAlias(
Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
$urlKey
);
return true;
}
}
return false;
}
}
이제 컨트롤러
app/code/local/Easylife/News/controllers/Adminhtml/News/ArticleController.php
<?php
class Easylife_News_Adminhtml_News_ArticleController
extends Mage_Adminhtml_Controller_Action {
protected function _construct(){
$this->setUsedModuleName('Easylife_News');
}
protected function _initArticle(){
$this->_title($this->__('News'))
->_title($this->__('Manage Articles'));
$articleId = (int) $this->getRequest()->getParam('id');
$article = Mage::getModel('easylife_news/article')
->setStoreId($this->getRequest()->getParam('store', 0));
if ($articleId) {
$article->load($articleId);
}
Mage::register('current_article', $article);
return $article;
}
public function indexAction(){
$this->_title($this->__('News'))
->_title($this->__('Manage Articles'));
$this->loadLayout();
$this->renderLayout();
}
public function newAction(){
$this->_forward('edit');
}
public function editAction(){
$articleId = (int) $this->getRequest()->getParam('id');
$article = $this->_initArticle();
if ($articleId && !$article->getId()) {
$this->_getSession()->addError(Mage::helper('easylife_news')->__('This article no longer exists.'));
$this->_redirect('*/*/');
return;
}
if ($data = Mage::getSingleton('adminhtml/session')->getArticleData(true)){
$article->setData($data);
}
$this->_title($article->getTitle());
Mage::dispatchEvent('easylife_news_article_edit_action', array('article' => $article));
$this->loadLayout();
if ($article->getId()){
if (!Mage::app()->isSingleStoreMode() && ($switchBlock = $this->getLayout()->getBlock('store_switcher'))) {
$switchBlock->setDefaultStoreName(Mage::helper('easylife_news')->__('Default Values'))
->setSwitchUrl($this->getUrl('*/*/*', array('_current'=>true, 'active_tab'=>null, 'tab' => null, 'store'=>null)));
}
}
else{
$this->getLayout()->getBlock('left')->unsetChild('store_switcher');
}
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->renderLayout();
}
public function saveAction(){
$storeId = $this->getRequest()->getParam('store');
$redirectBack = $this->getRequest()->getParam('back', false);
$articleId = $this->getRequest()->getParam('id');
$isEdit = (int)($this->getRequest()->getParam('id') != null);
$data = $this->getRequest()->getPost();
if ($data) {
$article = $this->_initArticle();
$articleData = $this->getRequest()->getPost('article', array());
$article->addData($articleData);
$article->setAttributeSetId($article->getDefaultAttributeSetId());
if ($useDefaults = $this->getRequest()->getPost('use_default')) {
foreach ($useDefaults as $attributeCode) {
$article->setData($attributeCode, false);
}
}
try {
$article->save();
$articleId = $article->getId();
$this->_getSession()->addSuccess(Mage::helper('easylife_news')->__('Article was saved'));
}
catch (Mage_Core_Exception $e) {
Mage::logException($e);
$this->_getSession()->addError($e->getMessage())
->setArticleData($articleData);
$redirectBack = true;
}
catch (Exception $e){
Mage::logException($e);
$this->_getSession()->addError(Mage::helper('easylife_news')->__('Error saving article'))
->setArticleData($articleData);
$redirectBack = true;
}
}
if ($redirectBack) {
$this->_redirect('*/*/edit', array(
'id' => $articleId,
'_current'=>true
));
}
else {
$this->_redirect('*/*/', array('store'=>$storeId));
}
}
public function deleteAction(){
if ($id = $this->getRequest()->getParam('id')) {
$article = Mage::getModel('easylife_news/article')->load($id);
try {
$article->delete();
$this->_getSession()->addSuccess(Mage::helper('easylife_news')->__('The articles has been deleted.'));
}
catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
$this->getResponse()->setRedirect($this->getUrl('*/*/', array('store'=>$this->getRequest()->getParam('store'))));
}
public function massDeleteAction() {
$articleIds = $this->getRequest()->getParam('article');
if (!is_array($articleIds)) {
$this->_getSession()->addError($this->__('Please select articles.'));
}
else {
try {
foreach ($articleIds as $articleId) {
$article = Mage::getSingleton('easylife_news/article')->load($articleId);
Mage::dispatchEvent('easylife_news_controller_article_delete', array('article' => $article));
$article->delete();
}
$this->_getSession()->addSuccess(
Mage::helper('easylife_news')->__('Total of %d record(s) have been deleted.', count($articleIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
public function massStatusAction(){
$articleIds = $this->getRequest()->getParam('article');
if(!is_array($articleIds)) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('easylife_news')->__('Please select articles.'));
}
else {
try {
foreach ($articleIds as $articleId) {
$article = Mage::getSingleton('easylife_news/article')->load($articleId)
->setStatus($this->getRequest()->getParam('status'))
->setIsMassupdate(true)
->save();
}
$this->_getSession()->addSuccess($this->__('Total of %d articles were successfully updated.', count($articleIds)));
}
catch (Mage_Core_Exception $e){
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('easylife_news')->__('There was an error updating articles.'));
Mage::logException($e);
}
}
$this->_redirect('*/*/index');
}
public function gridAction(){
$this->loadLayout();
$this->renderLayout();
}
protected function _isAllowed(){
return Mage::getSingleton('admin/session')->isAllowed('cms/easylife_news/article');
}
public function exportCsvAction(){
$fileName = 'articles.csv';
$content = $this->getLayout()->createBlock('easylife_news/adminhtml_article_grid')
->getCsvFile();
$this->_prepareDownloadResponse($fileName, $content);
}
public function exportExcelAction(){
$fileName = 'article.xls';
$content = $this->getLayout()->createBlock('easylife_news/adminhtml_article_grid')
->getExcelFile();
$this->_prepareDownloadResponse($fileName, $content);
}
public function exportXmlAction(){
$fileName = 'article.xml';
$content = $this->getLayout()->createBlock('easylife_news/adminhtml_article_grid')
->getXml();
$this->_prepareDownloadResponse($fileName, $content);
}
public function wysiwygAction() {
$elementId = $this->getRequest()->getParam('element_id', md5(microtime()));
$storeId = $this->getRequest()->getParam('store_id', 0);
$storeMediaUrl = Mage::app()->getStore($storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
$content = $this->getLayout()->createBlock('easylife_news/adminhtml_news_helper_form_wysiwyg_content', '', array(
'editor_element_id' => $elementId,
'store_id' => $storeId,
'store_media_url' => $storeMediaUrl,
));
$this->getResponse()->setBody($content->toHtml());
}
}
app/code/local/Easylife/News/controllers/ArticleController.php
-프론트 엔드 기사 컨트롤러
<?php
class Easylife_News_ArticleController
extends Mage_Core_Controller_Front_Action {
public function indexAction(){
$this->loadLayout();
$this->_initLayoutMessages('catalog/session');
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('checkout/session');
if (Mage::helper('easylife_news/article')->getUseBreadcrumbs()){
if ($breadcrumbBlock = $this->getLayout()->getBlock('breadcrumbs')){
$breadcrumbBlock->addCrumb('home', array(
'label' => Mage::helper('easylife_news')->__('Home'),
'link' => Mage::getUrl(),
)
);
$breadcrumbBlock->addCrumb('articles', array(
'label' => Mage::helper('easylife_news')->__('Articles'),
'link' => '',
)
);
}
}
$headBlock = $this->getLayout()->getBlock('head');
if ($headBlock) {
$headBlock->setTitle(Mage::getStoreConfig('easylife_news/article/meta_title'));
$headBlock->setKeywords(Mage::getStoreConfig('easylife_news/article/meta_keywords'));
$headBlock->setDescription(Mage::getStoreConfig('easylife_news/article/meta_description'));
}
$this->renderLayout();
}
protected function _initArticle(){
$articleId = $this->getRequest()->getParam('id', 0);
$article = Mage::getModel('easylife_news/article')
->setStoreId(Mage::app()->getStore()->getId())
->load($articleId);
if (!$article->getId()){
return false;
}
elseif (!$article->getStatus()){
return false;
}
return $article;
}
public function viewAction(){
$article = $this->_initArticle();
if (!$article) {
$this->_forward('no-route');
return;
}
Mage::register('current_article', $article);
$this->loadLayout();
$this->_initLayoutMessages('catalog/session');
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('checkout/session');
if ($root = $this->getLayout()->getBlock('root')) {
$root->addBodyClass('news-article news-article' . $article->getId());
}
if (Mage::helper('easylife_news/article')->getUseBreadcrumbs()){
if ($breadcrumbBlock = $this->getLayout()->getBlock('breadcrumbs')){
$breadcrumbBlock->addCrumb('home', array(
'label' => Mage::helper('easylife_news')->__('Home'),
'link' => Mage::getUrl(),
)
);
$breadcrumbBlock->addCrumb('articles', array(
'label' => Mage::helper('easylife_news')->__('Articles'),
'link' => Mage::helper('easylife_news/article')->getArticlesUrl(),
)
);
$breadcrumbBlock->addCrumb('article', array(
'label' => $article->getTitle(),
'link' => '',
)
);
}
}
$headBlock = $this->getLayout()->getBlock('head');
if ($headBlock) {
if ($article->getMetaTitle()){
$headBlock->setTitle($article->getMetaTitle());
}
else{
$headBlock->setTitle($article->getTitle());
}
$headBlock->setKeywords($article->getMetaKeywords());
$headBlock->setDescription($article->getMetaDescription());
}
$this->renderLayout();
}
public function rssAction(){
if (Mage::helper('easylife_news/article')->isRssEnabled()) {
$this->getResponse()->setHeader('Content-type', 'text/xml; charset=UTF-8');
$this->loadLayout(false);
$this->renderLayout();
}
else {
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
$this->getResponse()->setHeader('Status','404 File not found');
$this->_forward('nofeed','index','rss');
}
}
}
5 부 찾기
_beforeSave
그것은을 던졌습니다 그래서, 방법 Mage_Core_Exception
. 편집 할 때 Image에서 Array to String 변환 오류가 발생합니다. 나는 호출이 고려 setArticleData
되지 않기 때문에 , 특히 편집 할 때 이미지 데이터가 배열로 전송 된다고 생각합니다 . 추가 유효성 검사를 처리하는 코드 또는 접근 방식에서 이것이 실수입니까? 참고로 내 현재 작업 주위에 날 일을 포함 unset($articleData['image']);
전setArticleData
5 부
app/code/local/Easylife/News/controllers/Adminhtml/News/Article/AttributeController.php
-속성 컨트롤러
<?php
class Easylife_News_Adminhtml_News_Article_AttributeController
extends Mage_Adminhtml_Controller_Action {
protected $_entityTypeId;
public function preDispatch() {
parent::preDispatch();
$this->_entityTypeId = Mage::getModel('eav/entity')->setType(Easylife_News_Model_Article::ENTITY)->getTypeId();
}
protected function _initAction(){
$this->_title(Mage::helper('easylife_news')->__('Article'))
->_title(Mage::helper('easylife_news')->__('Attributes'))
->_title(Mage::helper('easylife_news')->__('Manage Attributes'));
$this->loadLayout()
->_setActiveMenu('cms/easylife_news/article_attributes');
return $this;
}
public function indexAction(){
$this->_initAction()
->renderLayout();
}
public function newAction(){
$this->_forward('edit');
}
public function editAction(){
$id = $this->getRequest()->getParam('attribute_id');
$model = Mage::getModel('easylife_news/resource_eav_attribute')
->setEntityTypeId($this->_entityTypeId);
if ($id) {
$model->load($id);
if (! $model->getId()) {
Mage::getSingleton('adminhtml/session')->addError(
Mage::helper('easylife_news')->__('This article attribute no longer exists'));
$this->_redirect('*/*/');
return;
}
// entity type check
if ($model->getEntityTypeId() != $this->_entityTypeId) {
Mage::getSingleton('adminhtml/session')->addError(
Mage::helper('easylife_news')->__('This article attribute cannot be edited.'));
$this->_redirect('*/*/');
return;
}
}
// set entered data if was error when we do save
$data = Mage::getSingleton('adminhtml/session')->getAttributeData(true);
if (! empty($data)) {
$model->addData($data);
}
Mage::register('entity_attribute', $model);
$this->_initAction();
$this->_title($id ? $model->getName() : Mage::helper('easylife_news')->__('New Article Attribute'));
$item = $id ? Mage::helper('easylife_news')->__('Edit Article Attribute')
: Mage::helper('easylife_news')->__('New Article Attribute');
$this->_addBreadcrumb($item, $item);
$this->renderLayout();
}
public function validateAction(){
$response = new Varien_Object();
$response->setError(false);
$attributeCode = $this->getRequest()->getParam('attribute_code');
$attributeId = $this->getRequest()->getParam('attribute_id');
$attribute = Mage::getModel('easylife_news/attribute')
->loadByCode($this->_entityTypeId, $attributeCode);
if ($attribute->getId() && !$attributeId) {
Mage::getSingleton('adminhtml/session')->addError(
Mage::helper('easylife_news')->__('Attribute with the same code already exists'));
$this->_initLayoutMessages('adminhtml/session');
$response->setError(true);
$response->setMessage($this->getLayout()->getMessagesBlock()->getGroupedHtml());
}
$this->getResponse()->setBody($response->toJson());
}
protected function _filterPostData($data){
if ($data) {
$helper = Mage::helper('easylife_news');
//labels
foreach ($data['frontend_label'] as & $value) {
if ($value) {
$value = $helper->stripTags($value);
}
}
//options
if (!empty($data['option']['value'])) {
foreach ($data['option']['value'] as &$options) {
foreach ($options as &$label) {
$label = $helper->stripTags($label);
}
}
}
//default value
if (!empty($data['default_value'])) {
$data['default_value'] = $helper->stripTags($data['default_value']);
}
if (!empty($data['default_value_text'])) {
$data['default_value_text'] = $helper->stripTags($data['default_value_text']);
}
if (!empty($data['default_value_textarea'])) {
$data['default_value_textarea'] = $helper->stripTags($data['default_value_textarea']);
}
}
return $data;
}
public function saveAction(){
$data = $this->getRequest()->getPost();
if ($data) {
$session = Mage::getSingleton('adminhtml/session');
$redirectBack = $this->getRequest()->getParam('back', false);
$model = Mage::getModel('easylife_news/resource_eav_attribute');
$helper = Mage::helper('easylife_news/article');
$id = $this->getRequest()->getParam('attribute_id');
//validate attribute_code
if (isset($data['attribute_code'])) {
$validatorAttrCode = new Zend_Validate_Regex(array('pattern' => '/^[a-z_0-9]{1,255}$/'));
if (!$validatorAttrCode->isValid($data['attribute_code'])) {
$session->addError(
Mage::helper('easylife_news')->__('Attribute code is invalid. Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'));
$this->_redirect('*/*/edit', array('attribute_id' => $id, '_current' => true));
return;
}
}
if ($id) {
$model->load($id);
if (!$model->getId()) {
$session->addError(
Mage::helper('easylife_news')->__('This attribute no longer exists'));
$this->_redirect('*/*/');
return;
}
// entity type check
if ($model->getEntityTypeId() != $this->_entityTypeId) {
$session->addError(
Mage::helper('easylife_news')->__('This attribute cannot be updated.'));
$session->setAttributeData($data);
$this->_redirect('*/*/');
return;
}
$data['attribute_code'] = $model->getAttributeCode();
$data['is_user_defined'] = $model->getIsUserDefined();
$data['frontend_input'] = $model->getFrontendInput();
} else {
$data['source_model'] = $helper->getAttributeSourceModelByInputType($data['frontend_input']);
$data['backend_model'] = $helper->getAttributeBackendModelByInputType($data['frontend_input']);
}
if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
$data['backend_type'] = $model->getBackendTypeByInput($data['frontend_input']);
}
$defaultValueField = $model->getDefaultValueByInput($data['frontend_input']);
if ($defaultValueField) {
$data['default_value'] = $this->getRequest()->getParam($defaultValueField);
}
//filter
$data = $this->_filterPostData($data);
$model->addData($data);
if (!$id) {
$model->setEntityTypeId($this->_entityTypeId);
$model->setIsUserDefined(1);
$model->setIsVisible(1);
}
try {
$model->save();
$session->addSuccess(
Mage::helper('easylife_news')->__('The article attribute has been saved.'));
/**
* Clear translation cache because attribute labels are stored in translation
*/
Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
$session->setAttributeData(false);
if ($redirectBack) {
$this->_redirect('*/*/edit', array('attribute_id' => $model->getId(),'_current'=>true));
} else {
$this->_redirect('*/*/', array());
}
return;
} catch (Exception $e) {
$session->addError($e->getMessage());
$session->setAttributeData($data);
$this->_redirect('*/*/edit', array('attribute_id' => $id, '_current' => true));
return;
}
}
$this->_redirect('*/*/');
}
public function deleteAction(){
if ($id = $this->getRequest()->getParam('attribute_id')) {
$model = Mage::getModel('easylife_news/resource_eav_attribute');
// entity type check
$model->load($id);
if ($model->getEntityTypeId() != $this->_entityTypeId) {
Mage::getSingleton('adminhtml/session')->addError(
Mage::helper('easylife_news')->__('This attribute cannot be deleted.'));
$this->_redirect('*/*/');
return;
}
try {
$model->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('easylife_news')->__('The article attribute has been deleted.'));
$this->_redirect('*/*/');
return;
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('attribute_id' => $this->getRequest()->getParam('attribute_id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(
Mage::helper('easylife_news')->__('Unable to find an attribute to delete.'));
$this->_redirect('*/*/');
}
protected function _isAllowed(){
return Mage::getSingleton('admin/session')->isAllowed('cms/easylife_news/article_attributes');
}
}
이제 도우미 :
app/code/local/Easylife/News/Helper/Data.php
-주요 도우미
<?php
class Easylife_News_Helper_Data
extends Mage_Core_Helper_Abstract {
public function convertOptions($options){
$converted = array();
foreach ($options as $option){
if (isset($option['value']) && !is_array($option['value']) && isset($option['label']) && !is_array($option['label'])){
$converted[$option['value']] = $option['label'];
}
}
return $converted;
}
}
app/code/local/Easylife/News/Helper/Article.php
-기사 도우미
<?php
class Easylife_News_Helper_Article
extends Mage_Core_Helper_Abstract {
public function getArticlesUrl(){
return Mage::getUrl('easylife_news/article/index');
}
public function getUseBreadcrumbs(){
return Mage::getStoreConfigFlag('easylife_news/article/breadcrumbs');
}
public function isRssEnabled(){
return Mage::getStoreConfigFlag('rss/config/active') && Mage::getStoreConfigFlag('easylife_news/article/rss');
}
public function getRssUrl(){
return Mage::getUrl('easylife_news/article/rss');
}
public function getFileBaseDir(){
return Mage::getBaseDir('media').DS.'article'.DS.'file';
}
public function getFileBaseUrl(){
return Mage::getBaseUrl('media').'article'.'/'.'file';
}
public function getAttributeSourceModelByInputType($inputType){
$inputTypes = $this->getAttributeInputTypes();
if (!empty($inputTypes[$inputType]['source_model'])) {
return $inputTypes[$inputType]['source_model'];
}
return null;
}
public function getAttributeInputTypes($inputType = null){
$inputTypes = array(
'multiselect' => array(
'backend_model' => 'eav/entity_attribute_backend_array'
),
'boolean' => array(
'source_model' => 'eav/entity_attribute_source_boolean'
),
'file' => array(
'backend_model' => 'easylife_news/article_attribute_backend_file'
),
'image' => array(
'backend_model' => 'easylife_news/article_attribute_backend_image'
),
);
if (is_null($inputType)) {
return $inputTypes;
} else if (isset($inputTypes[$inputType])) {
return $inputTypes[$inputType];
}
return array();
}
public function getAttributeBackendModelByInputType($inputType){
$inputTypes = $this->getAttributeInputTypes();
if (!empty($inputTypes[$inputType]['backend_model'])) {
return $inputTypes[$inputType]['backend_model'];
}
return null;
}
public function articleAttribute($article, $attributeHtml, $attributeName){
$attribute = Mage::getSingleton('eav/config')->getAttribute(Easylife_News_Model_Article::ENTITY, $attributeName);
if ($attribute && $attribute->getId() && !$attribute->getIsWysiwygEnabled()) {
if ($attribute->getFrontendInput() == 'textarea') {
$attributeHtml = nl2br($attributeHtml);
}
}
if ($attribute->getIsWysiwygEnabled()) {
$attributeHtml = $this->_getTemplateProcessor()->filter($attributeHtml);
}
return $attributeHtml;
}
protected function _getTemplateProcessor(){
if (null === $this->_templateProcessor) {
$this->_templateProcessor = Mage::helper('catalog')->getPageTemplateProcessor();
}
return $this->_templateProcessor;
}
}
app/code/local/Easylife/News/Helper/Image/Abstract.php
-추상적 이미지 도우미
<?php
abstract class Easylife_News_Helper_Image_Abstract
extends Mage_Core_Helper_Data {
protected $_placeholder = '';
protected $_subdir = '';
protected $_imageProcessor = null;
protected $_image = null;
protected $_openError = "";
protected $_keepFrame = false;
protected $_keepAspectRatio = true;
protected $_constrainOnly = true;
protected $_adaptiveResize = 'center'; // false|center|top|bottom
protected $_width = null;
protected $_height = null;
protected $_scheduledResize = null;
protected $_resized = false;
protected $_adaptiveResizePositions = array(
'center'=>array(0.5,0.5),
'top' =>array(1,0),
'bottom'=>array(0,1)
);
protected $_resizeFolderName = 'cache';
public function getImageBaseDir(){
return Mage::getBaseDir('media').DS.$this->_subdir.DS.'image';
}
public function getImageBaseUrl(){
return Mage::getBaseUrl('media').$this->_subdir.'/'.'image';
}
public function init(Varien_Object $object, $imageField = 'image'){
$this->_imageProcessor = null;
$this->_image = $object->getDataUsingMethod($imageField);
if(!$this->_image) {
$this->_image = '/'.$this->_placeholder;
}
$this->_widht = null;
$this->_height = null;
$this->_scheduledResize = false;
$this->_resized = false;
$this->_adaptiveResize = 'center';
try{
$this->_getImageProcessor()->open($this->getImageBaseDir().$this->_image);
}
catch (Exception $e){
$this->_openError = $e->getMessage();
try{
$this->_getImageProcessor()->open(Mage::getDesign()->getSkinUrl($this->_placeholder));
$this->_image = '/'.$this->_placeholder;
}
catch(Exception $e) {
$this->_openError .= "\n".$e->getMessage();
$this->_image = null;
}
}
return $this;
}
protected function _getImageProcessor() {
if (is_null($this->_imageProcessor)) {
$this->_imageProcessor = Varien_Image_Adapter::factory('GD2');
$this->_imageProcessor->keepFrame($this->_keepFrame);
$this->_imageProcessor->keepAspectRatio($this->_keepAspectRatio);
$this->_imageProcessor->constrainOnly($this->_constrainOnly);
}
return $this->_imageProcessor;
}
public function keepAspectRatio($value = null){
if (null !== $value) {
$this->_getImageProcessor()->keepAspectRatio($value);
return $this;
}
else {
return $this->_getImageProcessor()->keepAspectRatio();
}
}
public function keepFrame($value = null){
if (null !== $value) {
$this->_getImageProcessor()->keepFrame($value);
return $this;
}
else {
return $this->_getImageProcessor()->keepFrame();
}
}
public function keepTransparency($value = null){
if (null !== $value) {
$this->_getImageProcessor()->keepTransparency($value);
return $this;
}
else {
return $this->_getImageProcessor()->keepTransparency();
}
}
public function adaptiveResize($value = null){
if (null !== $value) {
$this->_adaptiveResize = $value;
if($value) {
$this->keepFrame(false);
}
return $this;
}
else {
return $this->_adaptiveResize;
}
}
public function constrainOnly($value = null){
if (null !== $value) {
$this->_getImageProcessor()->constrainOnly($value);
return $this;
}
else {
return $this->_getImageProcessor()->constrainOnly();
}
}
public function quality($value = null){
if (null !== $value) {
$this->_getImageProcessor()->quality($value);
return $this;
}
else {
return $this->_getImageProcessor()->quality();
}
}
public function backgroundColor($value = null){
if (null !== $value) {
$this->_getImageProcessor()-> backgroundColor($value);
return $this;
}
else {
return $this->_getImageProcessor()-> backgroundColor();
}
}
public function resize($width = null, $height = null) {
$this->_scheduledResize = true;
$this->_width = $width;
$this->_height = $height;
return $this;
}
protected function _getDestinationImagePrefix() {
if(!$this->_image) {
return $this;
}
$imageRealPath = "";
if($this->_scheduledResize) {
$width = $this->_width;
$height = $this->_height;
$adaptive = $this->adaptiveResize();
$keepFrame = $this->keepFrame();
$keepAspectRatio= $this->keepAspectRatio();
$constrainOnly = $this->constrainOnly();
$imageRealPath = $width.'x'.$height;
$options = "";
if(!$keepAspectRatio) {
$imageRealPath .= '-exact';
}
else {
if(!$keepFrame && $width && $height && ($adaptive !== false)) {
$adaptive = strtolower(trim($adaptive));
if(isset($this->_adaptiveResizePositions[$adaptive])) {
$imageRealPath .= '-'.$adaptive;
}
}
}
if($keepFrame) {
$imageRealPath .= '-frame';
$_backgroundColor = $this->backgroundColor();
if($_backgroundColor) {
$imageRealPath .= '-'.implode('-',$_backgroundColor);
}
}
if(!$constrainOnly) {
$imageRealPath .= '-zoom';
}
}
return $imageRealPath;
}
protected function _getDestinationPath() {
if(!$this->_image) {
return $this;
}
if($this->_scheduledResize) {
return $this->getImageBaseDir().DS.$this->_resizeFolderName.DS.$this->_getDestinationImagePrefix().DS.$this->_image;
} else {
return $this->getImageBaseDir().DS.$this->_image;
}
}
protected function _getImageUrl() {
if(!$this->_image) {
return false;
}
if($this->_scheduledResize) {
return $this->getImageBaseUrl().'/'.$this->_resizeFolderName.'/'.$this->_getDestinationImagePrefix().$this->_image;
}
else {
return $this->getImageBaseUrl().$this->_image;
}
}
protected function _doResize() {
if(!$this->_image || !$this->_scheduledResize || $this->_resized) {
return $this;
}
$this->_resized = true; //mark as resized
$width = $this->_width;
$height = $this->_height;
$adaptive = $width && $height &&
$this->keepAspectRatio() && !$this->keepFrame() &&
($this->adaptiveResize() !== false);
$adaptivePosition = false;
if($adaptive) {
$adaptive = strtolower(trim($this->adaptiveResize()));
if(isset($this->_adaptiveResizePositions[$adaptive])) {
$adaptivePosition = $this->_adaptiveResizePositions[$adaptive];
}
}
$processor = $this->_getImageProcessor();
if(!$adaptivePosition) {
$processor->resize($width, $height);
return $this;
}
//make adaptive resize
//https://github.com/wearefarm/magento-adaptive-resize/blob/master/README.md
$currentRatio = $processor->getOriginalWidth() / $processor->getOriginalHeight();
$targetRatio = $width / $height;
if ($targetRatio > $currentRatio) {
$processor->resize($width, null);
}
else {
$processor->resize(null, $height);
}
$diffWidth = $processor->getOriginalWidth() - $width;
$diffHeight = $processor->getOriginalHeight() - $height;
if($diffWidth || $diffHeight) {
$processor->crop(
floor($diffHeight * $adaptivePosition[0]), //top rate
floor($diffWidth / 2),
ceil($diffWidth / 2),
ceil($diffHeight * $adaptivePosition[1]) //bottom rate
);
}
return $this;
}
public function __toString(){
try{
if(!$this->_image) {
throw new Exception($this->_openError);
}
$imageRealPath = $this->_getDestinationPath();
if (!file_exists($imageRealPath)) {
$this->_doResize();
$this->_getImageProcessor()->save($imageRealPath);
}
return $this->_getImageUrl();
}
catch (Exception $e){
Mage::logException($e);
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAFr0lEQVR42rWXaUxUZxSGZVOKpWBRCGrSijBgDG1dagaxVgNSUqhAqq1CqzVVksb+sdZU0hgbfhQ1riEoiHFns4qVEYWglEWgVaBQLXRYJKzCzCA7KCpvz7njHbgz4AXSkryZYea73/Oe5Tv3zhQABtGfGcmCZPk/yYIZEuYIuDnJgeRKcn8pj/9Q7rw3M5g1moFpJGVnVxe0Wi20Oh107e1of/wYj1kdHejo7AR/z+oS1d0tqLunx6AeVm+vifoHBsAMZo1lYKVWq0NzyyO0PGrFo9Y2tLZp0KYRDA2bMjamN6c3OGzSxGwvmWDGWAasSR9qde0EbiVwG4E10AxnQw/XQ1nDUAYZZ2QU9fX1gRnMGtMAASTwMUvBGoYyQFoClmkJ5A0QhOHSlEtTbQoeAewVRdGy+kZoYDwGCGSacmOwKVQK6+9H/yh68uSJvAGGCGBTuACur6pCXUICssPDcXfHDvy5dy8KIyLQdOkSmh8+FNI8YCwCs54+fSpvgCNkOJeiwwieHROD3KBP8CDyJ9QePYLq/fuhjoqCml7L9/yI236+yI+L40hZDJRocHBwXAZGjTztq00o+mYbKiIj8cf2cGT6rIJKqUTakiW44a1EwdYtKNm1C/lfboBq0xcMM9GzZ8/kDRDMBJ5FkWeHrkPJD7uQvsYb177egr/LyzndQhPmpqYi2c0Fv23aiPxt25AZHIi8kycnZ4CaS1rz2lpcXbEUhd9ux7VVSmSfO8d1NaSY36cGBSJzrT9uhYYia+PnyFy/Dul+K6FpbmaoQc+fP5c3wF0twtnM5d27cfPTAEFJYRskcH69vjkMBaEh1BtBuEX9kbJIgav+q5EW6Iu0PXsYatCLFy/kDfCR4j7g1PIxSwwm+PogJCo98c/9+1L41s24FxaCIh8f5K3xwdVlC3CeTkTCewqkBvjhSthnkzMgwvn9WS9PpH7kh3Pve4yE0+brURLsixJqxOIPvKHyWoicM2eEWscrZuPI3Dk4tciNoRLJGuCB0q0fMMJQOb5YgQMz7BHj5mQYJvE+3shdqkDpvHkonz8PqmUKZJ8+zQAh0ti3HbDPbAriFusNDA0NscZngKFC9C8n2sm1foh6wwqHZ9vgdnIyYlZ5QeVojd/p0r+szHHZxR5Z8fGGCCtKSxHnZI1ouuZsyMcMlkjWAEN79dELEV/4ficOzZmOE7TpPlcnpDrb4A5d9oDgv7ja42ZcrAHOgLggfyTMskbsXBukROyeeAkYKkbPHd9UX48DHjMRa0lAgmfQJXenmiPFfQauH4+RwH89fBgXXGyRTOaOLpiFlsbGic8BHi5i9GyAm+7yoYOIUdghiZbfmmqBC++8iWiaCyJcXVaG6ABfpNCaLDJ32s0OV+ga2oP3Eu+QvJ/8A8mA3oDkvLP7Q8H+OOVB9ba2QKHja8icb4vEBTNx0cMB11xex10q071pFjhPa47QWuojPs58P+H7Cov/HyLGcjkD7Fw0IElf0oH9OOjpiBvudihztEG1uRnqSGoylE3RH/N0wsWon4WHFY1Gg5aWFjQ1NaGhoRH19Q1QqVR3iPEWyVzOgJh+iQFWQ10dTuz8DvsCVuOY0gXRXvNxNMQfsfRZjVotwGtpfBcWFqKoqAjldM+oqKhguJr2X0iayjw5Axy9sYGRE01yvvk7vo4HGEeel5fHnwt1r6qqYngj7b1IbD45Ayb1Z4DUgHS48BqGcb055Tk5uUIfVVdXIyMjQ2tra7uC9p7OHHkDBB7bgGn0/Bmv5ej5QaaOSlRcXIyamhoB7uzs7Ef72jJjogaM6//K9HPH63Q6qKkPKisrkZ6e3kiRL2c4yUzWgPjDZCIGAEgM0C8qNsBwbrh3STZSoLyB5QR8Ve1HKwGv5x7gsz5E8AL+HSie9YkYsHx5Rr25FJOUF2kuyUoCkjUgNcGZsJ6kpolDZrz6F2ZUsalEFcbPAAAAAElFTkSuQmCC';
}
}
}
app/code/local/Easylife/News/Helper/Article/Image.php
-기사 이미지 도우미
<?php
class Easylife_News_Helper_Article_Image
extends Easylife_News_Helper_Image_Abstract {
protected $_placeholder = 'images/placeholder/article.jpg';
protected $_subdir = 'article';
}
도우미들과 함께했습니다. 6 부 참조
Easylife_News_Helper_Image_Abstract
했지만 경로에 추가app/code/local/Easylife/News/Helper/Article/Image/Abstract.php
Easylife_News_Helper_Image_Abstract
틀린 오타를 발견 $this->_width = null;
했습니다init
6 부
app/design/adminhtml/default/default/layout/easylife_news.xml
-
<?xml version="1.0"?>
<layout>
<adminhtml_news_article_index>
<reference name="menu">
<action method="setActive">
<menupath>cms/easylife_news/article</menupath>
</action>
</reference>
<reference name="content">
<block type="easylife_news/adminhtml_article" name="article">
<block type="adminhtml/store_switcher" name="store_switcher" as="store_switcher">
<action method="setUseConfirm"><params>0</params></action>
</block>
</block>
</reference>
</adminhtml_news_article_index>
<adminhtml_news_article_grid>
<block type="core/text_list" name="root" output="toHtml">
<block type="easylife_news/adminhtml_article_grid" name="article_grid"/>
</block>
</adminhtml_news_article_grid>
<!-- Article add/edit action -->
<adminhtml_news_article_edit>
<update handle="editor"/>
<reference name="menu">
<action method="setActive">
<menupath>cms/easylife_news/article</menupath>
</action>
</reference>
<reference name="content">
<block type="easylife_news/adminhtml_article_edit" name="article_edit"></block>
</reference>
<reference name="left">
<block type="adminhtml/store_switcher" name="store_switcher" before="-"></block>
<block type="easylife_news/adminhtml_article_edit_tabs" name="article_tabs"></block>
</reference>
<reference name="head">
<action method="setCanLoadTinyMce"><load>1</load></action>
</reference>
<reference name="js">
<block type="core/template" name="catalog.wysiwyg.js" template="catalog/wysiwyg/js.phtml"/>
</reference>
</adminhtml_news_article_edit>
<adminhtml_news_article_attribute_index>
<reference name="content">
<block type="easylife_news/adminhtml_article_attribute" name="attribute_grid"></block>
</reference>
</adminhtml_news_article_attribute_index>
<adminhtml_news_article_attribute_edit>
<reference name="left">
<block type="easylife_news/adminhtml_article_attribute_edit_tabs" name="attribute_edit_tabs"></block>
</reference>
<reference name="content">
<block type="easylife_news/adminhtml_article_attribute_edit" name="attribute_edit_content"></block>
</reference>
<reference name="js">
<block type="adminhtml/template" name="attribute_edit_js" template="easylife_news/attribute/js.phtml">
<action method="setMainEntityName"><name>article</name></action>
</block>
</reference>
</adminhtml_news_article_attribute_edit>
</layout>
app/design/frontend/base/default/layout/easylife_news.xml
-프론트 엔드 레이아웃 파일
<?xml version="1.0"?>
<layout>
<easylife_news_article_index translate="label" module="easylife_news">
<label>Articles list</label>
<update handle="page_two_columns_left" />
<reference name="content">
<block type="easylife_news/article_list" name="article_list" template="easylife_news/article/list.phtml" />
</reference>
</easylife_news_article_index>
<easylife_news_article_view translate="label" module="easylife_news">
<label>Article view page</label>
<update handle="page_two_columns_left" />
<reference name="content">
<block type="easylife_news/article_view" name="article_view" template="easylife_news/article/view.phtml" />
</reference>
</easylife_news_article_view>
<easylife_news_article_rss translate="label" module="easylife_news">
<label>Articles rss feed</label>
<block type="easylife_news/article_rss" output="toHtml" name="easylife_news.article.rss" />
</easylife_news_article_rss>
<rss_index_index>
<reference name="content">
<block type="easylife_news/rss" name="news.rss" template="easylife_news/rss.phtml">
<action method="addFeed" ifconfig="easylife_news/article/rss" translate="label" module="easylife_news">
<label>Articles</label>
<url helper="easylife_news/article/getRssUrl" />
</action>
</block>
</reference>
</rss_index_index>
</layout>
이제 템플릿
app/design/adminhtml/default/default/template/easylife_news/grid.phtml
-그리드 템플릿
<div class="content-header">
<table cellspacing="0">
<tr>
<td style="width:50%;"><h3 class="icon-head <?php echo $this->getHeadClass();?>"><?php echo $this->getHeaderText(); ?></h3></td>
<td class="a-right">
<?php echo $this->getButtonsHtml() ?>
</td>
</tr>
</table>
</div>
<?php if( !Mage::app()->isSingleStoreMode() ): ?>
<?php echo $this->getChildHtml('store_switcher');?>
<?php endif;?>
<div>
<?php echo $this->getGridHtml() ?>
</div>
app/design/adminhtml/default/default/template/easylife_news/form/renderer/fieldset/element.phtml
-fieldset 요소 렌더러 (다른 상점보기의 체크 박스에 사용)
<?php $_element = $this->getElement() ?>
<?php $this->checkFieldDisable() ?>
<?php if ($_element->getType()=='hidden'): ?>
<tr>
<td class="hidden" colspan="100"><?php echo trim($_element->getElementHtml()) ?></td>
</tr>
<?php else: ?>
<tr>
<td class="label"><?php echo trim($this->getElementLabelHtml()) ?></td>
<td class="value">
<?php echo trim($this->getElementHtml()) ?>
<?php if ($_element->getNote()) : ?>
<p class="note"><?php echo $_element->getNote() ?></p>
<?php endif; ?>
</td>
<td class="scope-label"><span class="nobr"><?php echo $this->getScopeLabel() ?></span></td>
<?php if ($this->canDisplayUseDefault()): ?>
<td class="value use-default">
<input <?php if($_element->getReadonly()):?> disabled="disabled"<?php endif; ?> type="checkbox" name="use_default[]" id="<?php echo $_element->getHtmlId() ?>_default"<?php if ($this->usedDefault()): ?> checked="checked"<?php endif; ?> onclick="toggleValueElements(this, this.parentNode.parentNode)" value="<?php echo $this->getAttributeCode() ?>"/>
<label for="<?php echo $_element->getHtmlId() ?>_default" class="normal"><?php echo Mage::helper('easylife_news')->__('Use Default Value') ?></label>
</td>
<?php endif; ?>
</tr>
<?php endif; ?>
app/design/adminhtml/default/default/template/easylife_news/attribute/js.phtml
-추가 / 편집 속성 양식 관리에 필요한 일부 j
<script type="text/javascript">
//<![CDATA[
function saveAndContinueEdit(){
disableElements('save');
var activeTab = <?php echo $this->getMainEntityName()?>_attribute_tabsJsTabs.activeTab.id;
if (editForm.submit($('edit_form').action+'back/edit/tab/' + activeTab) == false) {
enableElements('save');
}
varienGlobalEvents.attachEventHandler('formValidateAjaxComplete', function (){
enableElements('save');
});
}
function saveAttribute(){
disableElements('save');
if (editForm.submit() == false){
enableElements('save');
}
varienGlobalEvents.attachEventHandler('formValidateAjaxComplete', function (){
enableElements('save');
});
}
function toggleApplyVisibility(select) {
if ($(select).value == 1) {
$(select).next('select').removeClassName('no-display');
$(select).next('select').removeClassName('ignore-validate');
} else {
$(select).next('select').addClassName('no-display');
$(select).next('select').addClassName('ignore-validate');
var options = $(select).next('select').options;
for( var i=0; i < options.length; i++) {
options[i].selected = false;
}
}
}
function checkOptionsPanelVisibility(){
if($('matage-options-panel')){
var panel = $('matage-options-panel');
if($('frontend_input') && ($('frontend_input').value=='select' || $('frontend_input').value=='multiselect')){
panel.show();
}
else {
panel.hide();
}
}
}
function bindAttributeInputType()
{
checkOptionsPanelVisibility();
switchDefaultValueField();
checkIsConfigurableVisibility();
if($('frontend_input') && ($('frontend_input').value=='select' || $('frontend_input').value=='multiselect' || $('frontend_input').value=='price')){
if($('is_filterable') && !$('is_filterable').getAttribute('readonly')){
$('is_filterable').disabled = false;
}
if($('is_filterable_in_search') && !$('is_filterable_in_search').getAttribute('readonly')){
$('is_filterable_in_search').disabled = false;
}
if($('backend_type') && $('backend_type').options){
for(var i=0;i<$('backend_type').options.length;i++){
if($('backend_type').options[i].value=='int') $('backend_type').selectedIndex = i;
}
}
}
else {
if($('is_filterable')){
$('is_filterable').selectedIndex=0;
$('is_filterable').disabled = true;
}
if($('is_filterable_in_search')){
$('is_filterable_in_search').disabled = true;
}
}
if ($('frontend_input') && ($('frontend_input').value=='multiselect'
|| $('frontend_input').value=='gallery'
|| $('frontend_input').value=='textarea')) {
if ($('used_for_sort_by')) {
$('used_for_sort_by').disabled = true;
}
}
else {
if ($('used_for_sort_by') && !$('used_for_sort_by').getAttribute('readonly')) {
$('used_for_sort_by').disabled = false;
}
}
setRowVisibility('is_wysiwyg_enabled', false);
if ($('frontend_input').value=='textarea') {
setRowVisibility('is_wysiwyg_enabled', true);
$('frontend_class').value = '';
$('frontend_class').disabled = true;
}
else if($('frontend_input').value=='text'){
if (!$('frontend_class').getAttribute('readonly')) {
$('frontend_class').disabled = false;
}
}
else{
$('frontend_class').value = '';
$('frontend_class').disabled = true;
}
switchIsFilterable();
}
function switchIsFilterable()
{
if ($('is_filterable')) {
if ($('is_filterable').selectedIndex == 0) {
$('position').disabled = true;
} else {
if (!$('position').getAttribute('readonly')){
$('position').disabled = false;
}
}
}
}
function switchDefaultValueField()
{
if (!$('frontend_input')) {
return;
}
var currentValue = $('frontend_input').value;
var defaultValueTextVisibility = false;
var defaultValueTextareaVisibility = false;
var defaultValueDateVisibility = false;
var defaultValueYesnoVisibility = false;
var scopeVisibility = true;
switch (currentValue) {
case 'select':
optionDefaultInputType = 'radio';
break;
case 'multiselect':
optionDefaultInputType = 'checkbox';
break;
case 'date':
defaultValueDateVisibility = true;
break;
case 'boolean':
defaultValueYesnoVisibility = true;
break;
case 'textarea':
defaultValueTextareaVisibility = true;
break;
case 'image':
defaultValueTextVisibility = false;
break;
case 'file':
defaultValueTextVisibility = false;
break;
default:
defaultValueTextVisibility = true;
break;
}
switch (currentValue) {
case 'image':
case 'file':
$('front_fieldset').previous().hide();
$('front_fieldset').hide();
setRowVisibility('is_required', false);
setRowVisibility('is_unique', false);
setRowVisibility('frontend_class', false);
break;
<?php foreach (Mage::helper('catalog')->getAttributeHiddenFields() as $type=>$fields): ?>
case '<?php echo $type; ?>':
<?php foreach ($fields as $one): ?>
<?php if ($one == '_front_fieldset'): ?>
$('front_fieldset').previous().hide();
$('front_fieldset').hide();
<?php elseif ($one == '_default_value'): ?>
defaultValueTextVisibility =
defaultValueTextareaVisibility =
defaultValueDateVisibility =
defaultValueYesnoVisibility = false;
<?php elseif ($one == '_scope'): ?>
scopeVisibility = false;
<?php else: ?>
setRowVisibility('<?php echo $one; ?>', false);
<?php endif; ?>
<?php endforeach; ?>
break;
<?php endforeach; ?>
default:
$('front_fieldset').previous().show();
$('front_fieldset').show();
setRowVisibility('is_required', true);
setRowVisibility('is_unique', true);
setRowVisibility('frontend_class', true);
setRowVisibility('is_configurable', true);
break;
}
setRowVisibility('default_value_text', defaultValueTextVisibility);
setRowVisibility('default_value_textarea', defaultValueTextareaVisibility);
setRowVisibility('default_value_date', defaultValueDateVisibility);
setRowVisibility('default_value_yesno', defaultValueYesnoVisibility);
setRowVisibility('is_global', scopeVisibility);
var elems = document.getElementsByName('default[]');
for (var i = 0; i < elems.length; i++) {
elems[i].type = optionDefaultInputType;
}
}
function setRowVisibility(id, isVisible)
{
if ($(id)) {
var td = $(id).parentNode;
var tr = $(td.parentNode);
if (isVisible) {
tr.show();
} else {
tr.blur();
tr.hide();
}
}
}
function checkIsConfigurableVisibility()
{
if (!$('is_configurable') || !$('is_global') || !$('frontend_input')) return;
if ($F('is_global')==1 && $F('frontend_input')=='select') {
setRowVisibility('is_configurable', true);
} else {
setRowVisibility('is_configurable', false);
}
}
function updateRequriedOptions()
{
if ($F('frontend_input')=='select' && $F('is_required')==1) {
$('option-count-check').addClassName('required-options-count');
} else {
$('option-count-check').removeClassName('required-options-count');
}
}
if($('frontend_input')){
Event.observe($('frontend_input'), 'change', updateRequriedOptions);
Event.observe($('frontend_input'), 'change', bindAttributeInputType);
Event.observe($('is_global'), 'change', checkIsConfigurableVisibility);
}
if ($('is_filterable')) {
Event.observe($('is_filterable'), 'change', switchIsFilterable);
}
if ($('is_required')) {
Event.observe($('is_required'), 'change', updateRequriedOptions);
}
bindAttributeInputType();
//]]>
</script>
app/design/frontend/base/default/template/easylife_news/article/list.phtml
-프론트 엔드 목록 템플릿-스타일이 필요할 수 있습니다.
<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
<?php $_articles = $this->getArticles(); ?>
<div class="page-title article-title">
<?php if(Mage::helper('easylife_news/article')->isRssEnabled()) : ?>
<a href="<?php echo Mage::helper('easylife_news/article')->getRssUrl();?>" class="link-rss"><?php echo Mage::helper('easylife_news')->__('Subscribe to RSS Feed')?></a>
<?php endif;?>
<h1><?php echo Mage::helper('easylife_news')->__('Articles') ?></h1>
</div>
<?php if ($_articles->getSize() > 0) :?>
<?php echo $this->getPagerHtml(); ?>
<div class="article-list-container">
<?php foreach ($_articles as $_article) : ?>
<div class="article-list-item">
<a href="<?php echo $_article->getArticleUrl()?>">
<?php echo $_article->getTitle();?>
</a><br />
</div>
<?php endforeach;?>
</div>
<?php echo $this->getPagerHtml(); ?>
<?php else : ?>
<?php echo Mage::helper('easylife_news')->__('There are no articles at this moment');?>
<?php endif;?>
app/design/frontend/base/default/template/easylife_news/article/view.phtml
-프론트 엔드 뷰 템플릿-일부 스타일링이 필요할 수 있습니다.
<?php $_article = $this->getCurrentArticle();?>
<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
<div class="page-title article-title">
<h1><?php echo $_article->getTitle(); ?></h1>
</div>
<div class="article-view">
<div class="article-title">
<?php echo Mage::helper('easylife_news')->__('Title');?>:<?php echo $_article->getTitle();?>
</div>
<div class="article-short_description">
<?php echo Mage::helper('easylife_news')->__('Short description');?>:<?php echo $_article->getShortDescription();?>
</div>
<div class="article-description">
<?php echo Mage::helper('easylife_news')->__('Description');?>:<?php echo $_article->getDescription();?>
</div>
<div class="article-publish_date">
<?php echo Mage::helper('easylife_news')->__("Publish Date");?>: <?php echo Mage::helper('core')->formatDate($_article->getPublishDate(), 'full');?>
</div>
</div>
app/design/frontend/base/default/template/easylife_news/rss.php
-RSS 템플릿
<?php $_feeds = $this->getFeeds();?>
<?php if ($_feeds): ?>
<table class="data-table rss-table" id="rss-table-news" style="margin-top:20px">
<col />
<col width="1" />
<thead>
<tr>
<th colspan="2"><?php echo Mage::helper('easylife_news')->__('News Feeds') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($_feeds as $_feed): ?>
<tr>
<td><?php echo $_feed->getLabel() ?></td>
<td><a href="<?php echo $_feed->getUrl() ?>" class="link-rss"><?php echo Mage::helper('easylife_news')->__('Get Feed'); ?></a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
이제 이미지 속성을 사용하려는 경우 자리 표시 자 이미지를 추가해야합니다.
이미지는에 배치해야합니다 skin/frontend/base/default/images/placeholder/article.jpg
. 기본 마 젠토 로고를 복사하여 배치하면됩니다.
그게 다야. 간단 하죠?