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
Solved! Go to Solution.
and you can't chain the load and delete, you have to:
$address = $this->address->getById($shippingId);
$this->address->delete($address);
I needed to use getById() instead of load()
But now I am getting an undefined method when trying to execute delete();