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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | $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!!
Leave a Reply