In Magento 2, there are some ways to create a new customer, fill the form in register page, create customer in backend, checkout … However, if you want to create account in some automation process, you will have to do it with code. This tutorial will show you how to create customer programmatically in Magento 2
Code snippet to create customer account
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // simulate frontend $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); // Create customer on specific website scope $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); $websiteId = $storeManager->getWebsite()->getWebsiteId() // Create new customer and Save $customer = $objectManager->get('Magento\Customer\Model\Customer'); $customer->setWebsiteId($websiteId); $customer->setFirstname("John"); $customer->setLastname("Doe"); $customer->setPassword(‘152452652’); $customer->save(); |
Code snippet to set address for customer account
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $addresss = $objectManager->get('\Magento\Customer\Model\Address'); $address->setCustomerId($customer->getId()) ->setFirstname("Demo") ->setLastname("Metagento") ->setCountryId('US') ->setPostcode("85000") ->setCity("City") ->setTelephone('0123456789') ->setFax('01234567') ->setCompany('Company') ->setStreet('Street') ->setIsDefaultBilling('1') ->setIsDefaultShipping('1') ->setSaveInAddressBook('1') $address->save(); |
Hope above code can help you save a little time on coding. In case you want to add many customers, you can apply the part of the code in a loop