Skip to content

How to make custom customer attribute filterable in the customer grid?

I’ve made a patch and this is the code for creating my customer custom attribute:

public function apply()
{
    $this->moduleDataSetup->getConnection()->startSetup();

    /** @var CustomerSetup $customerSetup */
    $customerSetup  = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
    $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
    $attributeSetId = $customerEntity->getDefaultAttributeSetId();

    $attributeSet       = $this->attributeSetFactory->create();
    $attributeGroupId   = $attributeSet->getDefaultGroupId($attributeSetId);

    try {
        $customerSetup->addAttribute(
            Customer::ENTITY,
            self::CUSTOMER_EMAIL_PREFERENCE,
            [
                'label' => 'Email preferences',
                'input' => 'multiselect',
                'type' => 'text',
                'source' => 'MyVendorCustomerModelCustomerAttributeSourceEmailPreference',
                'required' => false,
                'position' => 333,
                'visible' => true,
                'system' => false,
                'is_used_in_grid' => true,
                'is_visible_in_grid' => true,
                'is_filterable_in_grid' => true,
                'is_searchable_in_grid' => true,
                'backend' => ''
            ]
        );
    } catch (Exception $error) {
        echo $error->getMessage(); exit();
    }

    $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, self::CUSTOMER_EMAIL_PREFERENCE);
    $attribute->addData([
        'used_in_forms' => [
            'adminhtml_customer',
            'adminhtml_checkout',
            'customer_account_create',
            'customer_account_edit'
        ]
    ]);
    $attribute->addData([
        'attribute_set_id'   => $attributeSetId,
        'attribute_group_id' => $attributeGroupId

    ]);
    $attribute->save();

    $this->moduleDataSetup->getConnection()->endSetup();
}

This code creates the customer attribute and all is good, except that it does not appear in the filters! I’ve added this part:

        'is_used_in_grid' => true,
        'is_visible_in_grid' => true,
        'is_filterable_in_grid' => true,
        'is_searchable_in_grid' => true,

But still doesn’t work. Not sure that it is because of the multiselect type. I’ve made a new customer attribute , the only difference is that the input ‘s value is set to select . Like: 'input' => 'multiselect',. In this case I can filter it. Weird!

Would you please share your opinion, advice for this ?

Thanks a lot!