In this post I am going to explain how to add customer address programmatically in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $addressFactory;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Customer\Model\AddressFactory $addressFactory,
array $data = []
) {
$this->addressFactory = $addressFactory;
parent::__construct($context, $data);
}
public function addAddress($customerId) {
$firstName = 'John';
$lastName = 'Doe';
$address = $this->addressFactory->create();
$address->setCustomerId($customerId)
->setFirstname($firstName)
->setLastname($lastName)
->setCountryId('US')
->setRegionId('9')
->setPostcode('12345')
->setCity('City')
->setTelephone('1234567890')
->setFax('1234567890')
->setCompany('Company Name')
->setStreet(array(
'0' => 'Address Line 1 Text', // Required
'1' => 'Address Line 2 Text' // optional
))
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$address->save();
return __('Address added successfully');
} catch (Exception $e) {
return __('We can\'t save the customer address.');
}
}
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerId = 2;
$firstName = 'John';
$lastName = 'Doe';
$address = $objectManager->get('\Magento\Customer\Model\AddressFactory')->create();
$address->setCustomerId($customerId)
->setFirstname($firstName)
->setLastname($lastName)
->setCountryId('US')
->setRegionId('9')
->setPostcode('12345')
->setCity('City')
->setTelephone('1234567890')
->setFax('1234567890')
->setCompany('Company Name')
->setStreet(array(
'0' => 'Address Line 1 Text', // Required
'1' => 'Address Line 2 Text' // optional
))
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$address->save();
echo __('Address added successfully');
} catch (Exception $e) {
echo __('We can\'t save the customer address.');
}
Thats it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!



Leave a Reply