Magento – Product attribute backend_type changing from int to varchar :Magento 2.1.1

magento-2.1.1product

I have created one product attribute for custom sorting by InsatllData , but if am updating any field from admin the backend_type getting change from int to varchar because of that sorting getting disturbed.

Here is my InstallData.php

<?php

namespace Vendor\Productattr\Setup;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Resource\Eav\Attribute;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;


/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;
    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
        /* assign object to class global variable for use in other class methods */
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
         $setup->startSetup();
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);


        /**
         * Add attributes to the eav/attribute
       */
       $eavSetup->addAttribute(
         \Magento\Catalog\Model\Product::ENTITY,
       'sorting_attribute',
       [
       'type' => 'int',
        'backend' => '',
        'frontend' => '',
        'label' => 'Sorting Attribute',
        'input' => 'text',
        'class' => '',
        'source' => '',
        'global' => 1,
        'visible' => true,
        'required' => false,
        'user_defined' => true,
        'default' => 0,
        'searchable' => false,
        'filterable' => false,
        'comparable' => true,
        'visible_on_front' => false,
        'used_in_product_listing' => false,
        'unique' => false,
        'apply_to' => 'simple,configurable,virtual,bundle,downloadable,grouped',
        'group'=> 'General'
       ]
      );






       $setup->endSetup();
    }
}

Best Answer

I suggest you to use MYSQL trigger :

DELIMITER $$
CREATE TRIGGER topseller_int BEFORE UPDATE ON eav_attribute
FOR EACH ROW 
BEGIN
  IF NEW.attribute_code = 'topseller' THEN
    SET NEW.backend_type = 'int';
  END IF;
END;$$

DELIMITER ;

So that the backend-type of the attribute will always remains as you described. Hope it will help you.

Related Topic