While trying to delete address its redirecting to 404 page in Magento 2
-
22-02-2021 - |
Question
When I try to delete additional address in Magento 2 customer dashboard its redirecting to 404 Page. My URL format mentioned below.
/customer/address/delete/id/13/form_key/xkTKVSSxqip79bZ1
Solution
I got the solution. Change 'HttpPostActionInterface'
with 'HttpGetActionInterface'.
vendor/magento/module-customer/Controller/Address/delete.php use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
class Delete extends \Magento\Customer\Controller\Address implements HttpGetActionInterface
OTHER TIPS
It depends on what version of Magento 2 you are.
See this commit on GitHub. It added a check to enforce the request to be done with POST
method. The default js code will send the request trough a POST
request.
I don't see why your code does not work or how you're calling that GET request. But I would recommend simply changing your template to use a form instead of an anchor element.
<form action="<?php echo $block->getUrl("*/*/delete") ?>" method="POST">
<?= $block->getBlockHtml('formkey') ?>
<input type="hidden" name="id" value="<?= $_address->getId() ?>">
<button type="submit">
<?php echo $block->escapeHtml(__('Delete')) ?>
</button>
</form>
Obviously some styling will be needed.
Use preference :
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Customer\Controller\Address\Delete" type="Vendor\AddressDelete\Controller\Customer\Delete" />
</config>
Create a custom module and override this class,
namespace Vendor\AddressDelete\Controller\Customer;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
class Delete extends \Magento\Customer\Controller\Address implements HttpGetActionInterface
{
/**
* @return \Magento\Framework\Controller\Result\Redirect
*/
public function execute()
{
$addressId = $this->getRequest()->getParam('id', false);
if ($addressId && $this->_formKeyValidator->validate($this->getRequest())) {
try {
$address = $this->_addressRepository->getById($addressId);
if ($address->getCustomerId() === $this->_getSession()->getCustomerId()) {
$this->_addressRepository->deleteById($addressId);
$this->messageManager->addSuccess(__('You deleted the address.'));
} else {
$this->messageManager->addError(__('We can\'t delete the address right now.'));
}
} catch (\Exception $other) {
$this->messageManager->addException($other, __('We can\'t delete the address right now.'));
}
}
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
}