How to build a new customer/add address programmatically in Magento 2

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.

Get consulted by the industry's top Magento 2 experts to build your dream store

Here the below mentioned steps defines you how to build a new customer/add address programmatically in Magento 2:

How to build a new customer/add address in Magento 2 platform

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();

Last Update: February 5, 2021  

March 3, 2018   3849   Nandini Ramachandran    Magento 2 Tutorial, Magento 2.3, Operations    
Total 1 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn