We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
- Home
- Blog
- eCommerce Talk
- How To Create Customer & Add New Address Programmatically In Magento 2?
How To Create Customer & Add New Address Programmatically In Magento 2?
Would you like to learn some cool coding stuff in Magento 2? Then creating a customer and adding a new address in Magento 2 is something you should know.
In Magento 2, the customer account is created from the frontend via sign up. Or else, it can be created from the admin panel. Creating multiple customers with different addresses and segregating them into different groups is not an easy thing. The smart way to do it is programmatically in Magento 2 then by doing manually.
All you have to do is create a $customerInfo array and pass it to the block function. That’s it.
Refer the below code snippet that tells you how to create new customer and address programmatically in Magento 2:
Creating New Customer & Customer Address:
First, check if the customer is already existing or not having an email id. If it exists, then display “ customer already there” or add a new customer and the address of that customer.
<?php
declare(strict_types=1);
// Customer and customer address array
$customerInfo = [
'customer' => [
'firstname' => 'John',
'lastname' => 'Due',
'email' => '[email protected]', //customer email id
'password' => 'john123',
'prefix' => 'Mr',
'suffix' => ''
],
'address' => [
'firstname' => 'John',
'lastname' => 'Due',
'prefix' => 'Mr',
'suffix' => '',
'street' => '3148 Doctors Drive',
'city' => 'Los Angeles',
'country_id' => 'US',
'region' => 'California',
'region_id' => '12', // State region id
'postcode' => '90017',
'telephone' => '9876543210',
'save_in_address_book' => 1
]
];
/**
* @var $block \MageSpark\CreateCustomer\Block\CustomerAddress
*/
$block->createCustomer($customerInfo);
Adding To Block File:
Next, we pass the customer data from $customerinfo array to the block file
<?php
declare(strict_types=1);
namespace MageSpark\CreateCustomer\Block;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Phrase;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\StoreManagerInterface;
/**
* Class CustomerAddress
*
* @package MageSpark\CreateCustomer\Block
*/
class CustomerAddress extends Template
{
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var CustomerInterfaceFactory
*/
protected $customerFactory;
/**
* @var AddressInterfaceFactory
*/
protected $dataAddressFactory;
/**
* @var AddressRepositoryInterface
*/
protected $addressRepository;
/**
* @var EncryptorInterface
*/
protected $encryptor;
/**
* @var CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* CustomerAddress constructor.
*
* @param Context $context
* @param StoreManagerInterface $storeManager
* @param CustomerInterfaceFactory $customerFactory
* @param AddressInterfaceFactory $dataAddressFactory
* @param AddressRepositoryInterface $addressRepository
* @param EncryptorInterface $encryptor
* @param CustomerRepositoryInterface $customerRepository
* @param array $data
*/
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
CustomerInterfaceFactory $customerFactory,
AddressInterfaceFactory $dataAddressFactory,
AddressRepositoryInterface $addressRepository,
EncryptorInterface $encryptor,
CustomerRepositoryInterface $customerRepository,
array $data = []
) {
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
$this->dataAddressFactory = $dataAddressFactory;
$this->addressRepository = $addressRepository;
$this->encryptor = $encryptor;
$this->customerRepository = $customerRepository;
parent::__construct($context, $data);
}
/**
* Create customer
*
* @param $data
* @return Phrase
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function createCustomer($data)
{
$store = $this->storeManager->getStore();
$websiteId = $this->storeManager->getStore()->getWebsiteId();
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($data['customer']['email']); // load customer by email to check if customer is available or not
if (!$customer->getId()) {
/* create customer */
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($data['customer']['firstname'])
->setLastname($data['customer']['lastname'])
->setPrefix($data['customer']['prefix'])
->setMobile($data['customer']['mobile'])
->setEmail($data['customer']['email']);
$hashedPassword = $this->encryptor->getHash($data['customer']['password'], true);
$this->customerRepository->save($customer, $hashedPassword);
/* save address of customer */
$address = $this->dataAddressFactory->create();
$address->setFirstname($data['address']['firstname']);
$address->setLastname($data['address']['lastname']);
$address->setTelephone($data['address']['telephone']);
$street[] = $data['address']['street'];//pass street as array
$address->setStreet($street);
$address->setCity($data['address']['city']);
$address->setCountryId($data['address']['country_id']);
$address->setPostcode($data['address']['postcode']);
$address->setRegionId($data['address']['region_id']);
$address->setIsDefaultShipping(1);
$address->setIsDefaultBilling(1);
$address->setCustomerId($customer->getId());
try {
$this->addressRepository->save($address);
} catch (\Exception $e) {
return __('Error in shipping/billing address.');
}
} else {
return __('Customer is already exist!');
}
}
}
Run In Terminal SSH:
Finally, run the indexer command and display the customer in the admin panel.
php bin/magento indexer:reindex php bin/magento cache:flush
Conclusion:
Run the above code and implement it in your next eCommerce store project.
Comment below if you get any queries regarding the code or have a different approach to create customers in Magento 2. We’d be glad to assist you.