Magento 2 – How to Add New Column to Table customer_grid_flat

customermagento2

I want to add new column for table customer_entity and customer_grid_flat. please help me , how way to do it. thanks
my code :

    ...
    InstallSchema:
        $eavTable = $installer->getTable('customer_entity');
        $columns = [
            'custom_field' => [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                'length' => '6',
                'nullable' => false,
                'default' => 0,
                'comment' => 'del flg',
                'after' => 'gender'
            ]
        ];
        foreach ($columns as $name => $definition) {
            $connection->addColumn($eavTable, $name, $definition);
        }
...
    InstallData:
...
            $customerSetup->addAttribute('customer', 'custom_field', [
                'type' => 'static',/* Data type in which formate your value save in database*/
                'label' => __('custom_field'),
                'input' => 'text',
                'visible' => false,
                'required' => false,
                'is_used_in_grid' => true,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => false,
                'is_searchable_in_grid' => false
            ]);

            /**
             * @var EavSetupFactory $eavSetup
             */
            $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'custom_field');
            $attribute->setData('used_in_forms', [
                'adminhtml_customer'
            ]);
            $attribute->save();
    ...

I want to create the column customer_grid_flat.custom_field that get value from customer_entity.custom_field.

Best Answer

I find my solution here:
Step1:Create file your_module/etc/indexer.xml with content

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">
    <indexer id="customer_grid" view_id="dummy" class="Magento\Framework\Indexer\Action\Entity" primary="customer">
        <fieldset name="customer" source="Magento\Customer\Model\ResourceModel\Customer\Collection"
                  provider="Magento\Customer\Model\Indexer\AttributeProvider">
            <field name="custom_field" xsi:type="filterable" dataType="int"/>
        </fieldset>
    </indexer>
</config>

Step2: run command : php bin/magento indexer:reindex

Related Topic