系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
在Magento 2中以编程方式取消订单而不禁用URL安全密钥的步骤:
步骤 1:导航到以下路径:
app/code/VENDOR/EXTENSION/Controller/Adminhtml/Order/Cancel.php
并添加以下代码:
namespace VENDOR\EXTENSION\Controller\Adminhtml\Order; use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Sales\Controller\Adminhtml\Order\Cancel as CancelOrderController; class Cancel extends CancelOrderController implements HttpGetActionInterface { public function execute() { $resultRedirect = $this->resultRedirectFactory->create(); $order = $this->_initOrder(); if ($order) { try { $this->orderManagement->cancel($order->getEntityId()); $this->messageManager->addSuccessMessage(__('You canceled the order.')); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addErrorMessage(__('You have not canceled the item.')); $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e); } } return $resultRedirect->setPath('sales/order/index'); } }
步骤2:现在,移至以下路径:
app/code/VENDOR/EXTENSION/view/adminhtml/ui_component/sales_order_grid.xml
现在,添加以下代码:
<?xml version="1.0" encoding="UTF-8"?> <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> <columns name="sales_order_columns"> <actionsColumn name="actions" class="VENDOR\EXTENSION\UI\Component\Listing\Column\Actions"/> </columns> </listing>
步骤3:接下来,导航到以下路径:
app/code/vendor/extension/ui/Component/Listing/Column/Actions.php
并添加以下代码:
namespace VENDOR\EXTENSION\UI\Component\Listing\Column; use Magento\Sales\Ui\Component\Listing\Column\ViewAction; class Actions extends ViewAction { public function prepareDataSource(array $dataSource) { $dataSource = parent::prepareDataSource($dataSource); if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as & $item) { if (isset($item['entity_id'])) { $urlEntityParamName = $this->getData('config/urlEntityParamName') ?: 'entity_id'; $item[$this->getData('name')]['cancel'] = [ 'href' => $this->urlBuilder->getUrl( 'cancel/order/cancel', [ $urlEntityParamName => $item['entity_id'] ] ), 'label' => __('Cancel') ]; } } } return $dataSource; } }
步骤4:最后,导航到以下路径:
app/code/VENDOR/EXTENSION/etc/adminhtml/routes.xml
最后,添加以下代码:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="admin"> <route id="cancel" frontName="cancel"> <module name="VENDOR_EXTENSION" before="Magento_Sales" /> </route> </router> </config>
结论:
因此,希望每个人都能够以编程方式取消订单,而无需在Magento 2中禁用URL安全密钥。