Skip to content

Customer address not save programatically in magento 2

I tried to create and save customer address for a registered, logged user.

My code in controller is like below.

$addresss = $objectManager->get('MagentoCustomerModelAddressFactory');

    $address = $addresss->create();
    
    $address->setCustomerId(3)
    ->setFirstname("FirstName")
    ->setLastname('LastName')
    ->setCountryId("AE")
    ->setPostcode("10000")
    ->setCity('Panoi')
    ->setTelephone("074983118")
    ->setFax("443456789")
    ->setCompany("Company")
    ->setStreet("Street")
    ->setIsDefaultBilling('1')
    ->setIsDefaultShipping('1')
    ->setSaveInAddressBook('1');
    
    try{  
        $address->save();
    }catch (Exception $e) {
        Zend_Debug::dump($e->getMessage());
    }

This piece of code not running until the try block in my custom controller.

If i use the same file content in a custom php script everything working fine and new address is created and save in customer_address_entity table

Can some one help on this by explaining why is this happening. Situation like this how to debug the code.

I know using object manager is not encouraged, i tried other methods also nothing is seems working fine for me.