save default address programatically – magento2

save default address programatically – magento2
In this post we can add or update customer address programatically in magento2. In this code we pass customer address detail and update it.

hear we chaek user is login or not. Hear we check customer is login or any other not.

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

	// get login customer id 
	$customer_Session = $get_Instance->get('Magento\Customer\Model\Session');
	
	// pass your customer Id	
	$customer_Id = ""; 
	
	// check customer is login or not.
        if($customer_Session->isLoggedIn()) 
        {
	    $customer_Id = $customer_Session->getCustomer()->getId();	
	}
	
        // pass your login customer Id or your customer Id
    
	if($customer_Id != "") 
        {	
	    // Add Address For created customer
  	    $object_addres = $set_objectManager->get('\Magento\Customer\Model\AddressFactory');
	    $set_address = $object_addres->create();

	    $set_address->setCustomerId($customer_Id)  
		->setFirstname($setFirstname)
		->setLastname($setLastname)
		->setCountryId('AT')
		// if  country is USA theen need add state/province 
		//->setRegionId('1') 
		->setPostcode($setPostcode)
		->setCity($setCity)
		->setTelephone($setTelephone)
		->setFax($setFax)
		->setCompany('GMI')
		->setStreet($setStreet)
		->setIsDefaultBilling('1')
		->setIsDefaultShipping('1')
		->setSaveInAddressBook('1');
	    try{
		    $set_address->save();
	    }
	    catch (Exception $exception) {
		Zend_Debug::dump($exception->getMessage());
	    }
	}

Get login customer detail

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

// get login customer id 
$customer_Session = $get_Instance->get('Magento\Customer\Model\Session');

// pass your customer Id	
$customer_Id = ""; 

// check customer is login or not.
if($customer_Session->isLoggedIn()) 
{
	$customer_Id = $customer_Session->getCustomer()->getId();	
}
// Address data

$adress_data = array(); 

$get_customer = Mage::getModel('customer/customer');

// Load customer data
$get_customer->load($customer_Id);

// Get address of current 
$customer_address = $get_customer->getPrimaryBillingAddress();

// Do we add a new address
$is_New_Address = false;
if (!$customer_address) {
    $customer_address = Mage::getModel('customer/address');

    $customer_address->setCustomer($get_customer);
    $is_New_Address = true;
}

// data Append 
$customer_address->addData($adress_data);
$customer_address->save();

if ($is_New_Address) {
    // Add address to customer and save
    $get_customer->addAddress($customer_address)
        ->setDefaultBilling($customer_address->getId())
        ->save();
}

Also See This : Customer And Address Programmatically In Magento2