Skip to main content
Post Made Community Wiki by Marius
Source Link
Marius
  • 198.5k
  • 55
  • 424
  • 833

Part 2.

app/code/local/Easylife/News/Model/Attribute.php - the model for the article attributes

<?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 - the attribute resource model

<?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 - the attribute EAV resource model

<?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 - attribute collection model

<?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 - the setup resource model - used for adding the entities and attribtues:

<?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 - backend for file attributes if you decide to add one

<?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 - backend for image attributes if you decide to add one

<?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 - backend for url key attribute

<?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 - model that handles the admin global search

<?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;
    }
}

We're done with the models. Let's go on to blocks.
app/code/local/Easylife/News/Block/Rss.php - the general rss block

<?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 - the main article block

<?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 - the admin edit form

<?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');
        }
    }
}

Looks like there will be a part 3.....