In this post I am going to explain how to create customer programmatically in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $storeManager;
protected $customerFactory;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Model\CustomerFactory $customerFactory,
array $data = []
) {
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
parent::__construct($context, $data);
}
public function addCustomer($firstName, $lastName, $email, $password)
{
$store = $this->storeManager->getStore();
$websiteId = $this->storeManager->getWebsite()->getWebsiteId();
$customer = $this->customerFactory->create();
// Set website ID
$customer->setWebsiteId($websiteId);
// Set Store
$customer->setStore($store);
// Check if customer is already exists
if ($customer->loadByEmail($email)->getId()) {
return __('There is already an account with this email address "%1".', $email);
} else {
$customer->setEmail($email);
$customer->setFirstname($firstName);
$customer->setLastname($lastName);
$customer->setPassword($password);
$customer->setForceConfirmed(true);
// Save customer data
$customer->save();
// Send email
$customer->sendNewAccountEmail();
return __('Customer account with email %1 created successfully.', $email);
}
}2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$websiteId = $storeManager->getStore()->getWebsiteId();
$store = $storeManager->getStore();
$firstName = 'John';
$lastName = 'Doe';
$email = '[email protected]';
$password = 'John@1234';
$customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
// Set website ID
$customer->setWebsiteId($websiteId);
// Set Store
$customer->setStore($store);
// Check if customer is already exists
if ($customer->loadByEmail($email)->getId()) {
echo 'Customer with email ' . $email . ' is already registered.';
} else {
$customer->setEmail($email);
$customer->setFirstname($firstName);
$customer->setLastname($lastName);
$customer->setPassword($password);
$customer->setForceConfirmed(true);
// Save customer data
$customer->save();
// Send email
$customer->sendNewAccountEmail();
echo 'Customer with the email ' . $email . ' is successfully created.';
}Note: After creating customer you need to run indexer command to see a customer in the backend grid.
php bin/magento indexer:reindex php bin/magento cache:flush
That’s it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!



Leave a Reply