Question

How to get Customer collection filter by Full name or by keyword like admin grid of magento 2?

enter image description here

Was it helpful?

Solution

First, you have to call the Customer Collection factory and after that add addNameToSelect() function to that collection.

namespace {nameSpace};


class CustomCollection
{
    protected  $collectionFactory;
    public function __construct(
        \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $collectionFactory
    )
    {
        $this->collectionFactory = $collectionFactory;
    }

    public function getCustomCollectionWithFullName()
    {
        $customerName = 'John';
        $customerCollection = $this->collectionFactory->create();
        $customerCollection->addAttributeToSelect('*'); // use * for all field
        $customerCollection->addNameToSelect();
        // for == condition
        $customerCollection->getSelect() ->where(
            'name = ?',
            $customerName
        );
        // where like %V%

       // $customerCollection->where('name LIKE ?', '%' . $customerName . '%');

    }

}

OTHER TIPS

I found a way that works better(at least for me) and is based on the answer of Amit.

Just in a similar fashion, here is the code to include attributes for the collection:

$resultingCustomers = $this->customerCollectionFactory->create();
$resultingCustomers->addAttributeToSelect('*');
$resultingCustomers->addNameToSelect();

The difference is that instead of injecting an SQL WHERE clause into the collection like the answer of Amit, i used addAttributeToFilter:

$resultingCustomers->addAttributeToFilter('name',['like'=>($keyword . '%')]);

It works very well on Magento 2.4 and it is probably "The Magento Way" of doing it because you dont rely on low level SQL statements.

The final code snippet for this is below:

public function filterCustomersByFullname($keyword){

    $resultingCustomers = $this->customerCollectionFactory->create();
    $resultingCustomers->addAttributeToSelect('*');
    $resultingCustomers->addNameToSelect();

    $resultingCustomers->addAttributeToFilter('name',['like'=>($keyword . '%')]);

    return $resultingCustomers;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top