• 7th, Sep 2011

Magento, how to create new frontend type attribute for category

In this How To, I’m going to explain how to create a new category attribute to handle PDF files.
Magento category with new PDF attribute

a) Create a new category attribute

a1) Check your entity types

SELECT * FROM `eav_entity_type`

catalog_category is ID 9

a2) Insert attribute. Table: eav_attribute

entity_type_id = 9
attribute_code = category_pdf
attribute_model = NULL
backend_model = catalog/category_attribute_backend_file
backend_type = varchar
backend_table =
frontend_model =
frontend_input = file
frontend_label = Category PDF
frontend_class =
source_model =
is_required = 0
is_user_defined = 0
default_value =
is_unique = 0
note =

note the new row ID is 950

a3) Define attribute set and group. Make the relation between attribute and entity. Table: eav_entity_attribute

entity_type_id = 9 (Category)
attribute_set_id = 12 ("Default", attribute set - eav_attribute_set)
attribute_group_id = 7 ("General Information", first tab - eav_attribute_group)
attribute_id = 950 ("category_pdf", link with attribute)
sort_order = 0 (order position)

a4) Define attribute properties. Table: catalog_eav_attribute

frontend_input_renderer =
is_global = 1
is_visible = 1
is_searchable = 0
is_filterable = 0
is_comparable = 0
is_visible_on_front = 0
is_html_allowed_on_front = 0
is_used_for_price_rules = 1
is_filterable_in_search = 0
used_in_product_listing = 0
used_for_sort_by = 0
is_configurable = 1
apply_to
is_visible_in_advanced_search = 0
position = 0 (order position)
is_wysiwyg_enabled = 0
is_used_for_promo_rules = 1

a5) Remember to reindex Category Flat Data

b) Create a new frontend attribute type.

We will call it File to handle PDF files.

b1) Create the file /app/code/local/Mage/Catalog/Model/Category/Attribute/Backend/File.php


<?php
/**
 * Catalog category file attribute backend model
 *
 */
class Mage_Catalog_Model_Category_Attribute_Backend_File extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{

    /**
     * Save uploaded file and set its name to category
     *
     * @param Varien_Object $object
     */
    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::getBaseDir('media') . DS . 'files' . DS;

        try {
            $uploader = new Mage_Core_Model_File_Uploader($this->getAttribute()->getName());
            $uploader->setAllowedExtensions(array('pdf'));
            $uploader->setAllowRenameFiles(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() != Mage_Core_Model_File_Uploader::TMP_NAME_EMPTY) {
                Mage::logException($e);
            }
            /** @TODO ??? */
            return;
        }
    }
}

b2) Create the file /app/code/local/Varien/Data/Form/Element/File.php

<?php
/**
 * Category form input file element
 *
 */
class Varien_Data_Form_Element_File extends Varien_Data_Form_Element_Abstract
{

    /**
     * Enter description here...
     *
     * @param array $data
     */
    public function __construct($data)
    {
        parent::__construct($data);
        $this->setType('file');
    }

    /**
     * Enter description here...
     *
     * @return string
     */
    public function getElementHtml()
    {
        $html = '';

        if ($this->getValue()) {
            $url = $this->_getUrl();

            if( !preg_match("/^http\:\/\/|https\:\/\//", $url) ) {
                $url = Mage::getBaseUrl('media') . 'files' . DS . $url;
            }

            $html = '<a href="'.$url.'" target="_blank">';
            $html.= 'View file';
            $html.='</a> ';
        }
        $this->setClass('input-file');
        $html.= parent::getElementHtml();
        $html.= $this->_getDeleteCheckbox();

        return $html;
    }

    /**
     * Enter description here...
     *
     * @return string
     */
    protected function _getDeleteCheckbox()
    {
        $html = '';
        if ($this->getValue()) {
            $label = Mage::helper('core')->__('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;
    }

    /**
     * Enter description here...
     *
     * @return string
     */
    protected function _getHiddenInput()
    {
        return '<input type="hidden" name="'.parent::getName().'[value]" value="'.$this->getValue().'" />';
    }

    /**
     * Get image preview url
     *
     * @return string
     */
    protected function _getUrl()
    {
        return $this->getValue();
    }

    /**
     * Enter description here...
     *
     * @return string
     */
    public function getName()
    {
        return  $this->getData('name');
    }

}
Tested on Magento 1.5.1.0

TAGS: None

One Response to “Magento, how to create new frontend type attribute for category”


  1. peter
    on Oct 20th, 2011
    @ 4:53 pm

    Great post (and maybe only).

    I try to create new type attribute for products but with no success (blank page in admin panel on product page). Could you please help me with that?
    I did all similar to your tutorial (different id’s, backend_model, class).
    I will be thankful.

    regards

Leave a Reply

*

© 2010 unexpected[it]. All Rights Reserved.