How to Create customer and add new address programmatically in magento 2?

To creating customer and customer address programmatically in Magento 2 using below code snippet. Just Pass $customerInfo array to a block function .

Given below code checks, Customer is existed or not using email id. If the customer is new, Add a new customer and add given address to the same customer otherwise display already exist customer message.

In Block file, Pass customer required data from above $customerInfo array,

Run indexer command to see a customer in the admin panel,

 

2 Replies to “How to Create customer and add new address programmatically in magento 2?”

  1. /* save address as customer */
    $address = $this->dataAddressFactory->create();
    $address->setFirstname($data[‘address’][‘firstname’]);
    $address->setLastname($data[‘address’][‘lastname’]);
    $address->setTelephone($data[‘address’][‘telephone’]);

    $street[] = $data[‘address’][‘street’];//pass street as array
    $address->setStreet($street);

    $address->setCity($data[‘address’][‘city’]);
    $address->setCountryId($data[‘address’][‘country_id’]);
    $address->setPostcode($data[‘address’][‘postcode’]);
    $address->setRegionId($data[‘address’][‘region_id’]);
    $address->setIsDefaultShipping(1);
    $address->setIsDefaultBilling(1);
    $address->setCustomerId($customer->getId());
    try
    {
    $this->addressRepository->save($address);
    }

    at here how can I save only region,
    I tried with setRegion() method but its giving me error even It tried pass 1 param of ‘regionInterface’ but not working.

Leave a Reply