cancel
Showing results for 
Search instead for 
Did you mean: 

Delete all delivery addresses

SOLVED

Delete all delivery addresses

I am trying to delete the shipping address but I am getting an error I don't understand that is leading me to believe I am doing something wrong. I need to delete the shipping address and this is how I am doing it:

 

	public function __construct(
			\Magento\Customer\Model\CustomerRegistry $customerRegistry,
			\Magento\Backend\Block\Template\Context $context,
			UserContextInterface $userContext,
            \Magento\Customer\Model\AddressFactory $addressFactory,
            \Magento\Customer\Api\Data\RegionInterfaceFactory $regionInterfaceFactory,
            \Magento\Customer\Model\CustomerFactory $customerFactory,
            \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
            \Magento\Customer\Model\Address $address
	) {
		$this->customerRegistry = $customerRegistry;
		$this->userContext = $userContext;
        $this->addressFactory = $addressFactory;
        $this->regionInterfaceFactory = $regionInterfaceFactory;
        $this->customerRepository = $customerRepository;
        $this->address = $address;
	}

    public function deleteShippingAddress()
    {
    	$customerId = $this->userContext->getUserId();

    	if ($customerId) {

            $customer = $this->customerRepository->getById($customerId);
            $shippingId =  $customer->getDefaultShipping();

    		if ($shippingId) {

    			$address = $this->address->load($shippingId)->delete();
    			$response = array('response' => 'success', 'message' => 'Address deleted successfully.');

    		} else {

    			$response = array('response' => 'error', 'message' => 'Address Id not exists in Magento.');

    		}
    	} else {

    		$response = array('response' => 'error', 'message' => 'Customer not exists.');

    	}

    	return json_encode($response);
    }

 

This is giving me this error:

[message] => No such entity with %fieldName = %fieldValue
[parameters] => stdClass Object
(
[fieldName] => addressId
[fieldValue] => 22
)

[trace] => #0 /var/www/html/vendor/magento/module-customer/Model/AddressRegistry.php(49): Magento\Framework\Exception\NoSuchEntityException::singleField('addressId', '22')

 

Which is very confusing since I am retrieving the ID from the customer

 

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Delete all delivery addresses

and you can't chain the load and delete, you have to:                

$address = $this->address->getById($shippingId);
$this->address->delete($address);

View solution in original post

2 REPLIES 2

Re: Delete all delivery addresses

I needed to use getById() instead of load()

 

But now I am getting an undefined method when trying to execute delete();

Re: Delete all delivery addresses

and you can't chain the load and delete, you have to:                

$address = $this->address->getById($shippingId);
$this->address->delete($address);