本文档详细介绍了如何在 Magento 2 后台的订单详情页面添加一个自定义按钮,并配置其点击后的功能。通过创建自定义模块、配置路由、控制器和插件,可以实现自定义按钮的添加和功能的实现,并提供了完整的代码示例和配置步骤。
创建自定义模块
首先,创建一个自定义模块来实现所需的功能。按照 Magento 2 的模块结构,创建以下文件:
-
注册文件 (registration.php)
<?php MagentoFrameworkComponentComponentRegistrar::register( MagentoFrameworkComponentComponentRegistrar::MODULE, 'MG_Dropship', __DIR__ );
该文件用于注册模块。
-
模块配置文件 (etc/module.xml)
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="MG_Dropship" setup_version="1.0.0"/> </config>
该文件定义了模块的基本信息,例如模块名称和版本。
配置依赖注入 (di.xml)
使用 di.xml 文件配置依赖注入,以便在订单详情页面添加自定义按钮。
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework/ObjectManager/etc/config.xsd"> <type name="MagentoSalesBlockAdminhtmlOrderView"> <plugin name="addCustomButton" type="MGDropshipPluginSalesBlockAdminhtmlOrderButton"/> </type> </config>
这个配置将 MGDropshipPluginSalesBlockAdminhtmlOrderButton 插件应用到 MagentoSalesBlockAdminhtmlOrderView 块,允许我们修改订单详情页面的行为。
配置路由 (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="mg_dropship" frontName="mg_dropship"> <module name="MG_Dropship" /> </route> </router> </config>
该文件定义了一个名为 mg_dropship 的路由,其 frontName 为 mg_dropship。
创建控制器 (Controller/Adminhtml/Order/Index.php)
创建一个控制器来处理按钮点击后的逻辑。
<?php namespace MGDropshipControllerAdminhtmlOrder; use MagentoBackendAppAction; use MagentoBackendAppActionContext; use MagentoFrameworkControllerResultFactory; use MagentoSalesApiOrderRepositoryInterface; use PsrLogLoggerInterface; class Index extends Action { /** * @var OrderRepositoryInterface */ protected $orderRepository; /** * @var LoggerInterface */ protected $logger; /** * @param Context $context * @param OrderRepositoryInterface $orderRepository * @param LoggerInterface $logger */ public function __construct( Context $context, OrderRepositoryInterface $orderRepository, LoggerInterface $logger ) { $this->orderRepository = $orderRepository; $this->logger = $logger; parent::__construct($context); } /** * Execute action * * @throws MagentoFrameworkExceptionLocalizedException|Exception */ public function execute() { $orderId = $this->getRequest()->getParam('order_id'); $resultredirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); try { $order = $this->orderRepository->get($orderId); // TODO: Do something with the order $this->messageManager->addSuccessMessage(__('We did something!')); } catch (MagentoFrameworkExceptionLocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (Exception $e) { $this->messageManager->addErrorMessage(__('We can't process your request' . $e->getMessage())); $this->logger->critical($e); } return $resultRedirect->setPath( 'sales/order/view', [ 'order_id' => $orderId ] ); } /** * @return bool */ protected function _isAllowed() { return $this->_authorization->isAllowed('MG_Dropship::order_dosomething'); } }
这个控制器获取订单ID,执行一些操作(TODO部分),并重定向回订单详情页面。
创建插件 (Plugin/Adminhtml/Order/Button.php)
创建一个插件来向订单详情页面添加自定义按钮。
<?php namespace MGDropshipPluginSalesBlockAdminhtmlOrder; use MagentoSalesBlockAdminhtmlOrderView as OrderView; class Button { public function beforeSetLayout(OrderView $subject) { if ($subject->getOrder()) { $message = __('Are you sure you want to Do Something?'); $subject->addButton( 'do_something', [ 'label' => __('Do Something'), 'class' => 'do_something', 'onclick' => "confirmSetLocation('{$message}', '{$subject->getUrl('mg_dropship/order/index', ['order_id' => $subject->getOrder()->getId()])}')" ] ); } } }
这个插件使用 beforeSetLayout 方法在订单详情页面添加一个名为 “Do Something” 的按钮。点击该按钮会弹出一个确认对话框,然后重定向到 mg_dropship/order/index 路由,并传递订单ID。
清理缓存和重新部署
完成以上步骤后,需要清理 Magento 2 的缓存并重新部署静态内容。
php bin/magento cache:clean php bin/magento setup:upgrade php bin/magento setup:di:compile php bin/magento setup:static-content:deploy -f
注意事项
- 确保模块已启用。
- 检查文件路径和命名空间是否正确。
- 根据实际需求修改控制器中的逻辑。
- 如果开启了 “Add Secret Key to URLs”,请确保URL包含正确的 Form Key。
总结
通过以上步骤,你可以在 Magento 2 后台的订单详情页面成功添加一个自定义按钮,并配置其点击后的功能。这个方法可以扩展到其他页面和功能,实现更复杂的自定义需求。