You can create Customer address using Programmatically for any existing customer in Magento.
For Create Customer address, you must have a customer created in Magento store. Based on existing customer id, We can create customer address programmatically.
You need to refer below code snippet to create customer address,
<?php
namespace Rbj\CustomerAddress\Block;
use Exception;
use Magento\Framework\View\Element\Template;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Framework\View\Element\Template\Context;
class CustomerAddress extends Template
{
/**
* @var AddressInterfaceFactory
*/
private $dataAddressFactory;
/**
* @var AddressRepositoryInterface
*/
private $addressRepository;
public function __construct(
Context $context,
AddressInterfaceFactory $dataAddressFactory,
AddressRepositoryInterface $addressRepository,
array $data = []
) {
$this->dataAddressFactory = $dataAddressFactory;
$this->addressRepository = $addressRepository;
parent::__construct($context,$data);
}
/**
* save address as customer
* @return void
*/
public function createAddress(): void
{
$address = $this->dataAddressFactory->create();
$address->setFirstname('Rakesh');
$address->setLastname('Jesadiya');
$address->setTelephone('telephone');
$street[] = 'street 1';//pass street as array
$street[] = 'street 2';
$address->setStreet($street);
$regionId = 23; // For Illinois
$customerId = 5; // Pass dynamica Value
$address->setCity('chicago');
$address->setCountryId('US');
$address->setPostcode('60606');
$address->setRegionId($regionId);
$address->setIsDefaultShipping(1);
$address->setIsDefaultBilling(1);
$address->setCustomerId($customerId);
try {
$this->addressRepository->save($address);
} catch (Exception $exception) {
}
}
}
AddressRepositoryInterface used to save Customer address Programmatically.
You need to pass Customer id $customerId dynamically in the above function for creating a customer address.
You can see the new Customer address from the admin panel.
Go To Admin panel, Login with credentials,
Click on Left navigation, Customers -> All Customers
Click Your Customers and Check the Addresses tab from left.
You can see a new customer address.
