To build a new customer, we have multiple and add new customer address through the admin interface, customer register on the frontend here, I will show you how to build a new customer and add customer address programmatically in Magento 2.
Build your dream Multi-vendor marketplace platform like Amazon here, check this out!!!
Here, the below-mentioned steps define how to build a new customer/add address programmatically in Magento 2:
How to build a new customer and address in Magento 2
Step 1: Build a new 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("[email protected]"); $customer->setFirstname("FirstName"); $customer->setLastname("LastName"); $customer->setPassword("123456789); $customer->save(); echo 'Create customer successfully'.$customer->getId();
Step 2: Add a new customer address
$addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory'); $address = $addresss->create(); $address->setCustomerId($customer->getId()) ->setFirstname(FirstName) ->setLastname(LastName) ->setCountryId(VN) ->setPostcode(10000) ->setCity(HaNoi) ->setTelephone(1234567890) ->setFax(123456789) ->setCompany(Company) ->setStreet(Street) ->setIsDefaultBilling('1') ->setIsDefaultShipping('1') ->setSaveInAddressBook('1') $address->save();
Looking to build an online marketplace website with all eCommerce features? Click here and get started!!!
Leave a Reply