Wednesday, 13 September 2017

Magento Custom Category Attribute File

1.Your category attribute installer:
$installer = $this;
$installer->startSetup();
$installer->addAttribute('catalog_category', 'custom_flv', array(
    'group'                    => 'General',
    'label'                    => 'Some File',
    'input'                    => 'image',
    'type'                     => 'varchar',
    'backend'                  => 'some_module/category_attribute_backend_file',
    'global'                   => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible'                  => true,
    'required'                 => false,
    'user_defined'             => true,
    'order'                    => 20
));
$installer->endSetup();


2.\app\code\local\Some\Module\Model\Category\Attribute\Backend\File.php

class Some_Module_Model_Category_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::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS;
        try {
            $uploader = new Mage_Core_Model_File_Uploader($this->getAttribute()->getName());

            $uploader->setAllowedExtensions(array('flv','pdf','doc','txt','sql'));
            $uploader->setAllowRenameFiles(true);
            $result = $uploader->save($path);
            //allowed extensions here
            $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);
            }
            return;
        }
    }
}

3./app/code/local/Some/Module/etc/config.xml
<global>
    <resources>
        <some_module_setup>
            <setup>
                <module>Some_Module</module>
                <class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class>
            </setup>
        </some_module_setup>
    </resources>
    <!--another nodes -->
 </global>

No comments:

Post a Comment