How To Index Product Attributes With Source Model In Flat Table In Magento 2?

How To Index Product Attributes With Source Model In Flat Table Magento 2

First of all, the product attributes might not be added to the flat table in Magento 2 since it lacks some methods: Magento\Eav\Model\Entity\Attribute\Source\Table. In this tutorial, we will help you to add missing products attributes with the source model to the flat table. Let’s get started!

Step 1: Enable the flat catalog (Accessing your admin panel > Stores > Configuration > Catalog > Catalog > Storefront > Set “Use Flat Catalog Product” to Yes)

Step 2: Create the product attributes with source model

$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
   $eavSetup->addAttribute(
                \Magento\Catalog\Model\Product::ENTITY,
                'attribute_test',
                [
                    'group' => 'General',
                    'type' => 'int',
                    'label' => 'attribute_test',
                    'backend' => '',
                    'input' => 'select',
                    'wysiwyg_enabled' => false,
                    'source' => 'Vendor\Module\Model\Entity\Attribute\Source\SourceTest',
                    'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                    'required' => false,
                    'sort_order' => 5,
                    'visible' => true,
                    'user_defined' => false,
                    'default' => '',
                    'searchable' => false,
                    'filterable' => false,
                    'comparable' => false,
                    'visible_on_front' => false,
                    'used_in_product_listing' => true,
                    'unique' => false,
                    'attribute_set' => 'Package',
                    'option' => [
                        'values' => [],
                    ]
                ]
            );

Content of the file Vendor\Module\Model\Entity\Attribute\Source\SourceTest:

<?php

namespace Vendor\Module\Model\Entity\Attribute\Source;

use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ObjectManager;

class SourceTest extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory
     */
    protected $_attrOptionFactory;

   
    public function __construct(
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory $attrOptionFactory
    )
    {
        $this->_attrOptionFactory = $attrOptionFactory;
    }

    /**
     * Get a text for option value
     *
     * @param string|integer $value
     * @return string|bool
     */
    public function getOptionText($value)
    {
        foreach ($this->getAllOptions() as $option) {
            if ($option['value'] == $value) {
                return $option['label'];
            }
        }
        return false;
    }

    /**
     * Get all options
     *
     * @return array
     */
    public function getAllOptions()
    {
        $this->_options = [
            ['label' => 'Select', 'value' => ''],
            ['label' => 'Test1', 'value' => '1'],
            ['label' => 'Test2', 'value' => '2']
        ];
        return $this->_options;
    }

    /**
     * Retrieve Column(s) for Flat
     *
     * @return array
     */
    public function getFlatColumns()
    {
        $columns = [];
        $attributeCode = $this->getAttribute()->getAttributeCode();
        $isMulti = $this->getAttribute()->getFrontend()->getInputType() == 'multiselect';

        $type = $isMulti ? \Magento\Framework\DB\Ddl\Table::TYPE_TEXT : \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER;
        $columns[$attributeCode] = [
            'type' => $type,
            'length' => $isMulti ? '255' : null,
            'unsigned' => false,
            'nullable' => true,
            'default' => null,
            'extra' => null,
            'comment' => $attributeCode . ' column',
        ];
        if (!$isMulti) {
            $columns[$attributeCode . '_value'] = [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                'length' => 255,
                'unsigned' => false,
                'nullable' => true,
                'default' => null,
                'extra' => null,
                'comment' => $attributeCode . ' column',
            ];
        }

        return $columns;
    }

    /**
     * Retrieve Indexes for Flat
     *
     * @return array
     */
    public function getFlatIndexes()
    {
        $indexes = [];

        $index = sprintf('IDX_%s', strtoupper($this->getAttribute()->getAttributeCode()));
        $indexes[$index] = ['type' => 'index', 'fields' => [$this->getAttribute()->getAttributeCode()]];

        $sortable = $this->getAttribute()->getUsedForSortBy();
        if ($sortable && $this->getAttribute()->getFrontend()->getInputType() != 'multiselect') {
            $index = sprintf('IDX_%s_VALUE', strtoupper($this->getAttribute()->getAttributeCode()));

            $indexes[$index] = [
                'type' => 'index',
                'fields' => [$this->getAttribute()->getAttributeCode() . '_value'],
            ];
        }

        return $indexes;
    }
}

Step 3: Reindex ./bin/magento index:reindex

Step 4: Check the result in table catalog_product_flat_1 to see whether your product attributes are added to the flat table

We have shown you some easy steps to add custom product attributes with source model to the flat table in Magento 2. If you find any issues when following these steps, please leave a comment below. See you in the next tutorial!

Related Posts:

Magento 2: Placing Billing Address Right Under Shipping Address In Checkout

How To Configure & Install Elasticsearch In Magento 2?

Magento 2.3.1 Official Release – HIGHLIGHTS

How to Quickly Add Customer Attributes in Magento 2

Leave a Reply

Your email address will not be published. Required fields are marked *