Normally in Magento, new customers are created through sign up form on website or via admin panel. It’s time consuming task especially when you want to create numerous customers and assign to some customer groups from different countries, migrating to Magento, it’s better to do with code rather creating them manually.
Detailed code to create customers programmatically in Magento 2:
- Create New Customer:
- Add Address to Customer:
$objectManager = $bootstrap->getObjectManager(); $url = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface'); $state = $objectManager->get('\Magento\Framework\App\State'); $state->setAreaCode('frontend'); // Customer Factory to Create Customer $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory'); $websiteId = $storeManager->getWebsite()->getWebsiteId() $store = $storeManager->getStore(); // Get Store ID $storeId = $store->getStoreId(); // Instantiate object (this is the most important part) $customer = $customerFactory->create(); $customer->setWebsiteId($websiteId); $customer->setEmail("hello@example.com"); $customer->setFirstname("John"); $customer->setLastname("Doe"); $customer->setPassword(‘152452652’); $customer->save(); echo 'Create customer successfully'.$customer->getId();
$addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory'); $address = $addresss->create(); $address->setCustomerId($customer->getId()) ->setFirstname(FirstName) ->setLastname(LastName) ->setCountryId(US) ->setPostcode(85001) ->setCity(Pheonix) ->setTelephone(1234567890) ->setFax(123456789) ->setCompany(Company) ->setStreet(Street) ->setIsDefaultBilling('1') ->setIsDefaultShipping('1') ->setSaveInAddressBook('1') $address->save();
With the above code, I hope you can create the new customers more comfortably saving a lot of time. Here the most important thing is to keep your eye on required fields and pass them with your code. In case of adding multiple customers together, place the same code in a loop and create them within the blink of an eye. Let me know if you require my assistance or help while implementing, your comments are always welcomed.