10

I have successfully created a customer programmatically. Now I want to add an address to this customer. How can I do this programmatically?

1
  • how did you created a customer programatically please Commented Oct 31, 2018 at 12:58

4 Answers 4

25

Using Magento\Customer\Api\AddressRepositoryInterface; you can create customer address.

namespace {NameSpace};

/**
 * Description of Address
 */
class Address {

/**
 * @var Magento\Customer\Api\Data\AddressInterfaceFactory
 */
protected $addressDataFactory;

/**
 * @var \Magento\Customer\Api\AddressRepositoryInterface
 */
protected $addressRepository;

public function __construct(
    \Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
    \Magento\Customer\Api\Data\AddressInterfaceFactory $addressDataFactory
) {
    $this->addressRepository = $addressRepository;
    $this->addressDataFactory = $addressDataFactory;
}

public function saveCustomer()
{
    $address = $this->addressDataFactory->create();
    $address->setFirstname($firstName)
            ->setLastname($lastName)
            ->setCountryId($countryId)
            ->setRegionId($regionId)
            ->setRegion($regionName)
            ->setCity($city)
            ->setPostcode($postcode)
            ->setCustomerId($customerId)
            ->setStreet($street)
            ->setTelephone($telephone);

    $this->addressRepository->save($address);
}
6
  • 1
    Great! let's take this next level...according to my requirement...how can i check that if given address is already exist or not?if yes,then i've to create address else i've to skip. Commented May 29, 2019 at 15:27
  • +1 for the answer. I also want to add the Landmark in my address. I tried by adding ->setLandmark($landmark) but it doesn't work for me. How could I set it along with this? Commented Feb 3, 2020 at 9:48
  • @Amit Bera How to save custom attributes? ->setMycustom() not working
    – Kanika
    Commented Mar 13, 2020 at 5:06
  • 1
    Good answer, saved my time +1:) Commented Mar 25, 2020 at 11:21
  • It's really helpful code but can you say me how can assign default address multiple customer id's programmatically Commented Apr 7, 2021 at 11:30
5

Please try with following code.

$customerId = 10

$addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');

$address = $addresss->create();

$address->setCustomerId($customerId)

->setFirstname('test')

->setLastname('last')

->setCountryId('IN')

->setPostcode(10000)

->setCity('Bangalore')

->setTelephone('1234567890')

->setCompany('BNG')

->setStreet('XYZ street')

->setIsDefaultBilling('1')

->setIsDefaultShipping('1')

->setSaveInAddressBook('1')

$address->save();
2
  • Upvoted... (y) its also working Commented Feb 13, 2020 at 11:52
  • This one worked fine for me . Commented Jan 28, 2021 at 10:53
1

Try it, It works for me.

private function save_customer($JsonParam) {
        echo "<PRE>";
        print_r($JsonParam);
        exit;
        $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->loadByEmail($JsonParam->Email);
        if (!$customer->getId()) {
            $customer->setEmail($JsonParam->Email);
            $customer->setFirstname($JsonParam->FirstName);
            $customer->setLastname($JsonParam->LastName);
            $customer->setPassword('Admin@123');
            $customer->save();

            $addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');
            $address = $addresss->create();
            $address->setCustomerId($customer->getId())
                    ->setFirstname($JsonParam->FirstName)
                    ->setLastname($JsonParam->LastName)
                    ->setCountryId($JsonParam->Country)
                    ->setPostcode($JsonParam->Zip)
                    ->setCity($JsonParam->City)
                    ->setState($JsonParam->State)
                    ->setTelephone($JsonParam->Phone)
                    ->setCompany('Arhamsoft Pvt. Ltd.')
                    ->setStreet($JsonParam->Address1 . " / " . $JsonParam->Address2)
                    ->setIsDefaultBilling(false)
                    ->setIsDefaultShipping('1')
                    ->setSaveInAddressBook('1');
            $address->save();

            $addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');
            $address = $addresss->create();
            $address->setCustomerId($customer->getId())
                    ->setFirstname($JsonParam->FirstName)
                    ->setLastname($JsonParam->LastName)
                    ->setCountryId($JsonParam->BillingCountry)
                    ->setPostcode($JsonParam->BillingZip)
                    ->setCity($JsonParam->BillingCity)
                    ->setState($JsonParam->BillingState)
                    ->setTelephone($JsonParam->Phone)
                    ->setCompany('Arhamsoft Pvt. Ltd.')
                    ->setStreet($JsonParam->BillingAddress1 . " / " . $JsonParam->BillingAddress2)
                    ->setIsDefaultBilling('1')
                    ->setIsDefaultShipping(false)
                    ->setSaveInAddressBook('1');
            $address->save();

            echo 'Create customer successfully' . $customer->getId(); exit; 
        } else {
            //email already exists 
            echo 'Email already exists'; exit; 
        }
    }
2
  • Does this update the NULL value of customer_entity table column "default_shipping", "default_billing"?
    – MSQ
    Commented Feb 13, 2020 at 10:09
  • how to do that?
    – MSQ
    Commented Feb 13, 2020 at 10:09
0

I Did check and its working proper

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');

        $address = $addresss->create();

        $address->setCustomerId($customerId)

            ->setFirstname($FirstName)

            ->setLastname($LastName)

            ->setCountryId($countryid)

            ->setPostcode($postcode)

            ->setCity($city)

            ->setTelephone($telephone)

            ->setFax($fax)

            ->setCompany($Company)

            ->setStreet($Street)

            ->setRegion($region)

            ->setSaveInAddressBook('1');

        $address->save();

And if you want to set default billing & shipping address just add 2 line like below

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');

        $address = $addresss->create();

        $address->setCustomerId($customerId)

            ->setFirstname($FirstName)

            ->setLastname($LastName)

            ->setCountryId($countryid)

            ->setPostcode($postcode)

            ->setCity($city)

            ->setTelephone($telephone)

            ->setFax($fax)

            ->setCompany($Company)

            ->setStreet($Street)

            ->setRegion($region)

            ->setIsDefaultBilling('1')

            ->setIsDefaultShipping('1')

            ->setSaveInAddressBook('1');

        $address->save();
1
  • Dont use $objectManager
    – matinict
    Commented Mar 18, 2021 at 4:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.