Magento 2:在订单详情页添加自定义按钮并实现功能

DDD
发布: 2025-08-08 16:14:01
原创
472人浏览过

magento 2:在订单详情页添加自定义按钮并实现功能

本文档详细介绍了如何在 Magento 2 后台的订单详情页面添加一个自定义按钮,并配置其点击后的功能。通过创建自定义模块、配置路由、控制器和插件,可以实现自定义按钮的添加和功能的实现,并提供了完整的代码示例和配置步骤。

创建自定义模块

首先,创建一个自定义模块来实现所需的功能。按照 Magento 2 的模块结构,创建以下文件:

  1. 注册文件 (registration.php)

    <?php
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'MG_Dropship',
        __DIR__
    );
    登录后复制

    该文件用于注册模块。

  2. 模块配置文件 (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="Magento\Sales\Block\Adminhtml\Order\View">
       <plugin name="addCustomButton" type="MG\Dropship\Plugin\Sales\Block\Adminhtml\Order\Button"/>
   </type>
</config>
登录后复制

这个配置将 MG\Dropship\Plugin\Sales\Block\Adminhtml\Order\Button 插件应用到 Magento\Sales\Block\Adminhtml\Order\View 块,允许我们修改订单详情页面的行为。

配置路由 (routes.xml)

为了处理自定义按钮的点击事件,需要配置路由。

Type
Type

生成草稿,转换文本,获得写作帮助-等等。

Type 83
查看详情 Type
<?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 MG\Dropship\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;

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 \Magento\Framework\Exception\LocalizedException|\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 (\Magento\Framework\Exception\LocalizedException $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 MG\Dropship\Plugin\Sales\Block\Adminhtml\Order;

use Magento\Sales\Block\Adminhtml\Order\View 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 后台的订单详情页面成功添加一个自定义按钮,并配置其点击后的功能。这个方法可以扩展到其他页面和功能,实现更复杂的自定义需求。

以上就是Magento 2:在订单详情页添加自定义按钮并实现功能的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号