Filter customers by custom attribute in admin grid
-
23-01-2021 - |
Question
I added custom attribute to customer and now I want to filter customers by that attribute in admin grid (admin->customers). I want to user see only customers which custom attribute has specific value.
Filtering should be done before loading all customers, not with Filters button.
To be more specific, I just need a way to dump some rows from customers list based on some condition.
Solution 2
I found solution.
I filter customers in Vendor\Module\Ui\Component\Listing\Column in prepareDataSource(array $dataSource) function where I print the value of custom attribute. As I have $dataSource which contains all customers, I remove from array the one that I don't want to show based on condition.
Important think is that after removing from array, you have to reindex array.
OTHER TIPS
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $customerSetupFactory;
public function __construct(
CustomerSetupFactory $customerSetupFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(Customer::ENTITY, 'your_attributes', [
'label' => 'Your Label',
'input' => 'select',
'required' => false,
'sort_order' => 100,
'visible' => true,
'system' => false,
'type' => 'int',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
'is_used_in_grid' => true,
'is_visible_in_grid' => true,
'is_filterable_in_grid' => true, //This is what you looking
'is_searchable_in_grid' => true,
'option' => ['values' => ['Text1', 'Text2']],
]);
$setup->endSetup();
}
}