Question

I need to retrieve the customer object belonging to a certain (mobile) phone number. How can I do this in Magento?

And how can I get a customer by phone number when a phone number was entered by end users and can be written in different ways?

For instance:

  • +1 310-954-8012
  • 1 (310) 954-8012
  • 1-310-954-8012
  • 13109548012
Was it helpful?

Solution

You can do this via the customer address collection as the phone number is part of a customer's address.

If the phone number given by $phoneNumber and the one in the customer's address literally match, you can simply do:

$customer = Mage::getResourceModel('customer/address_collection')
    ->addAttributeToSelect('telephone')
    ->addAttributeToFilter('telephone', $phoneNumber)
    ->getFirstItem()->getCustomer();
if ($customer !== false) {
    // Do stuff...
}

If you need to filter out miscellaneous characters, you need to do this on both sides, input and SQL, so you could do:

$charFilter = array('+', ' ', '(', ')', '-');
$phoneNumber = str_replace($charFilter, '', $phoneNumber);

// Build up SQL string replacements    
$sqlFilter = 'at_telephone.value';
foreach ($charFilter as $_char) {
    $sqlFilter = sprintf('REPLACE(%s, "%s", "")', $sqlFilter, $_char);
}

// Build collection
$collection = Mage::getResourceModel('customer/address_collection')
    ->addAttributeToSelect('telephone')
    ->addAttributeToFilter('telephone', array('notnull' => true));
$collection->getSelect()->where($sqlFilter . ' = ?', $phoneNumber);

// Get customer
$customer = $collection->getFirstItem()->getCustomer();
if ($customer !== false) {
    // Do stuff...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top