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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $websiteId = $storeManager->getStore()->getWebsiteId(); $store = $storeManager->getStore(); $firstName = 'John'; $lastName = 'Doe'; $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.
1 2 | php bin/magento indexer:reindex php bin/magento cache:flush |
That’s it. Enjoy…
Recent Comments