PHP Magento Tips

How to Create Custom Product Attribute In Magento With Install Script

Rate this posting:
{[['']]}

This is successfully tested tutorial on how to install custom product attributes (eav attributes) with Magento Install upgrade script. It can easily be adapted for other entities’ attributes. It’s also a good starting point for general install scripts.

Step 1:

In app/etc/modules/Training_Animal.xml add below code:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Training_Animal>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Core />
             </depends>
        </Training_Animal>
    </modules>
</config>

Step 2:

In app/code/local/Training/Animal/etc/config.xml add below code:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Training_Animal>
            <version>1.0.3</version>
        </Training_Animal>
    </modules>
    <global>
        <resources>
            <training_animal_setup>
                <setup>
                    <module>Training_Animal</module>
                    <class>Training_Animal_Model_Resource_Setup</class>
                </setup>
                <connection>
                      <use>core_setup</use>
                </connection>
            </training_animal_setup>
            <training_animal_write>
                <connection>
                  <use>core_write</use>
                </connection>
             </training_animal_write>
        </resources>
        <models>
            <training_animal>
                <class>Training_Animal_Model</class>
                <resourceModel>training_animal_resource</resourceModel>
            </training_animal>
            <training_animal_resource>
                <class>Training_Animal_Model_Resource</class>
                <entities>
                    <animal>
                        <table>training_animal_entity</table>
                    </animal>
                </entities>
            </training_animal_resource>
        </models>
    </global>
    <adminhtml>
    <fieldsets>
      <attribute_insalled>
        <create>1</create>
        <update>1</update>
      </attribute_insalled>
    </fieldsets>
  </adminhtml>
</config> 

Step 3:

In app/code/local/Training/Animal/Model/Animal.php add below code:

<?php

// app/code/local/Training/Animal/Model/Animal.php
class Training_Animal_Model_Animal extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('training_animal/animal');
    }   
}

Step 4:

In app/code/local/Training/Animal/Model/Resource/Animal.php add below code:

<?php 
// app/code/local/Training/Animal/Model/Mysql4/Animal.php
class Training_Animal_Model_Resource_Animal extends Mage_Core_Model_Resource_Db_Abstract
{
    protected function _construct()
    {
        $this->_init('training_animal/animal', 'entity_id');
    }
}

Step 5:


In app/code/local/Training/Animal/Model/Resource/Setup.php add below code:


<?php
// app/code/local/Training/Animal/Model/Resource/Setup.php
class Training_Animal_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup
{
}

Step 6:

In app/code/local/Training/Animal/Model/Resource/Animal/Collection.php add below code:

<?php

// app/code/local/Training/Animal/Model/Resource/Animal/Collection.php
class Training_Animal_Model_Resource_Animal_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    protected $_joinedFields = array();
    
    protected function _construct()
    {
        parent::_construct();
        $this->_init('training_animal/animal');
    }
    protected function _toOptionArray($valueField='animal', $labelField='name', $additional=array())
    {
        return parent::_toOptionArray($valueField, $labelField, $additional);
    }
    protected function _toOptionHash($valueField='animal', $labelField='name')
    {
        return parent::_toOptionHash($valueField, $labelField);
    }
    public function getSelectCountSql()
    {
        $countSelect = parent::getSelectCountSql();
        $countSelect->reset(Zend_Db_Select::GROUP);
        return $countSelect;
    }
} 

Step 7:

In app/code/local/Training/Animal/sql/training_animal_setup/install-1.0.0.php add below code:

<?php

$this->startSetup();
$table = $this->getConnection()
    ->newTable($this->getTable('training_animal/animal'))
    ->addColumn(
        'entity_id',
        Varien_Db_Ddl_Table::TYPE_INTEGER,
        null,
        array(
            'identity'  => true,
            'nullable'  => false,
            'primary'   => true,
        ),
        'Animal ID'
    )
    ->addColumn(
        'name',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(
            'nullable'  => false,
        ),
        'name'
    )
    ->addColumn(
        'type',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(
            'nullable'  => false,
        ),
        'type'
    )
    ->addColumn(
        'edible',
        Varien_Db_Ddl_Table::TYPE_INTEGER, null,
        array(
            'nullable'  => false,
            'unsigned'  => true,
        ),
        'edible'
    )
    ->addColumn(
        'comment',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(
            'nullable'  => false,
        ),
        'comment'
    )
    ->addColumn(
        'updated_at',
        Varien_Db_Ddl_Table::TYPE_TIMESTAMP,
        null,
        array(),
        'Animal Modification Time'
    )
    ->addColumn(
        'created_at',
        Varien_Db_Ddl_Table::TYPE_TIMESTAMP,
        null,
        array(),
        'Animal Creation Time'
    ) 
    ->setComment('Animal Table');
$this->getConnection()->createTable($table);
$this->endSetup();

Step 8:

In app/code/local/Training/Animal/sql/training_animal_setup/upgrade-1.0.0-1.0.1.php add below code:

<?php 
$installer = $this;
$installer->startSetup();
$installer->getConnection()
    ->addColumn($installer->getTable('training_animal/animal'), 'trainable', array(
        'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
        'length' => 1,
        'unsigned'  => true,
        'default' => 0,
        'nullable' => false,
        'after'     => 'edible',
        'comment' => 'trainable'
    ));
$installer->endSetup();

Step 9:


In app/code/local/Training/Animal/sql/training_animal_setup/upgrade-1.0.1-1.0.2.php add below code:

<?php
$installer = Mage::getResourceModel ( 'catalog/setup', 'catalog/setup' );

$installer->startSetup ();

// addAttribute uses _prepareValues()
$data = array (
        'label' => 'Script_Generated_MS_Option',
        'type' => 'varchar', // multiselect uses comma sep storage
        'input' => 'multiselect',
        'backend' => 'eav/entity_attribute_backend_array',
        'frontend' => 'training_animal/entity_attribute_frontend_list',
        'required' => 0,
        'user_defined' => 1,
        'group' => 'Prices',
        'unique' => 0, // eav_attribute.is_unique unique value required
        'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, // catalog_eav_attribute.is_global (products only) scope
        'visible' => 1, // catalog_eav_attribute.is_visible (products only) visible on admin, setting to false stops import of this attribute
        'visible_on_front' => 1, // catalog_eav_attribute.is_visible_on_front (products only) visible on frontend (store) attribute table
        'used_in_product_listing' => 0, // catalog_eav_attribute.used_in_product_listing (products only) made available in product listing
        'searchable' => 0, // catalog_eav_attribute.is_searchable (products only) searchable via basic search
        'visible_in_advanced_search' => 0, // catalog_eav_attribute.is_visible_in_advanced_search (products only) searchable via advanced search
        'filterable' => 0, // catalog_eav_attribute.is_filterable (products only) use in layered nav
        'filterable_in_search' => 0, // catalog_eav_attribute.is_filterable_in_search (products only) use in search results layered nav
        'comparable' => 0, // catalog_eav_attribute.is_comparable (products only) comparable on frontend
        'is_html_allowed_on_front' => 1, // catalog_eav_attribute.is_visible_on_front (products only) seems obvious, but also see visible
        'apply_to' => 'simple,configurable', // catalog_eav_attribute.apply_to (products only) which product types to apply to
        'is_configurable' => 0, // catalog_eav_attribute.is_configurable (products only) used for configurable products or not
        'used_for_sort_by' => 0, // catalog_eav_attribute.used_for_sort_by (products only) available in the 'sort by' menu
        'position' => 0, // catalog_eav_attribute.position (products only) position in layered naviagtion
        'used_for_promo_rules' => 0,
        'option' => array (
                'order' => array (
                        'one' => 1,
                        'two' => 2,
                        'three' => 3 
                ),
                'value' => array (
                        'one' => array (
                                0 => 'Some Label One',
                                2 => 'Alt One' 
                        ),
                        'two' => array (
                                0 => 'Some Label Two',
                                2 => 'Alt Two' 
                        ),
                        'three' => array (
                                0 => 'Some Label Three',
                                2 => 'Alt Three' 
                        ) 
                        // 2 => ... the store id (eg English, german, etc ..)
                                ) 
        ) 
);

$installer->addAttribute ( 'catalog_product', 'attribute_insalled', $data );
// Done:
$installer->endSetup (); 


Step 10:

In app/code/local/Training/Animal/sql/training_animal_setup/upgrade-1.0.2-1.0.3.php add below code:

<?php
$installer = Mage::getResourceModel ( 'catalog/setup', 'catalog/setup' );
$installer->startSetup ();
// updateAttributes DOES NOT uses _prepareValues();

$installer->updateAttribute ( 'catalog_product', 'attribute_installed', 'group', 'Prices' );
$installer->endSetup ();

Step 11:

In app/code/local/Training/Animal/Model/Entity/Attribute/Frontend/List.php add below code:
(you can find enough hint at app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php)

<?php

class Training_Animal_Model_Entity_Attribute_Frontend_List
  extends Mage_Eav_Model_Entity_Attribute_Frontend_Abstract
{
  
  public function getValue(Varien_Object $object)
  {
      $value = $object->getData($this->getAttribute()->getAttributeCode());
     
      if ($this->getConfigField('input')=='multiselect') {
          $value = $this->getOption($value);
          if (is_array($value)) {
              $output = '<ul><li>';
            $output .= implode('</li><li>', $value);
            $output .= '</li></ul>';
            return $output;
          }
      }
      return $value;
  }
  
}


Now run any of your front end page. And check core_resources, eav_attribute and training_animal_entity table.

Also in backend find new multiselect option under "Price" tab for any product.

Now Edit any product and choose multiselect option and save the product.

Product option will display in frontend under "Additional Information" Tab.

Also Swith the store language from English to French and check option value will also change.

Download This from https://github.com/vijayrami/training_animal_sql

Reference for attribute settings:

https://makandracards.com/magento/6721-product-attribute-addition
http://krikasoft.com/create-new-product-attribute-with-options/
Tag : Magento
0 Comments On "How to Create Custom Product Attribute In Magento With Install Script"

Back To Top