Magento2前端销售订单查看页添加自定义Tab报错咨询
Magento2 前端订单页添加自定义Tab报错解决方案
报错Call to a member function getRealOrderId() on null的根因是:你用到的Magento\Sales\Block\Order\Info块依赖系统注册表中预加载的订单对象,你的自定义控制器没有完成订单的校验和注入逻辑,导致块读取订单对象为空。
按照以下步骤修改即可解决:
1. 修正自定义控制器逻辑
替换Controller/Index/Index.php代码,增加订单读取、权限校验、注册到系统注册表的逻辑:
<?php namespace Infopro\CustomSection\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\Registry; use Magento\Sales\Model\OrderFactory; use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\Controller\Result\ForwardFactory; class Index extends \Magento\Framework\App\Action\Action { protected $registry; protected $orderFactory; protected $customerSession; protected $forwardFactory; public function __construct( Context $context, Registry $registry, OrderFactory $orderFactory, CustomerSession $customerSession, ForwardFactory $forwardFactory ) { $this->registry = $registry; $this->orderFactory = $orderFactory; $this->customerSession = $customerSession; $this->forwardFactory = $forwardFactory; parent::__construct($context); } public function execute() { $orderId = $this->getRequest()->getParam('order_id'); if (!$orderId) { return $this->forwardFactory->create()->forward('noroute'); } $order = $this->orderFactory->create()->load($orderId); // 校验订单归属,防止越权访问 if (!$order->getId() || $order->getCustomerId() != $this->customerSession->getCustomerId()) { return $this->forwardFactory->create()->forward('noroute'); } // 注册订单到系统注册表,供订单相关块读取 $this->registry->register('current_order', $order); $this->_view->loadLayout(); $this->_view->renderLayout(); } }
2. 修正Tab跳转链接传参
修改sales_order_info_links.xml,给链接块增加自动携带订单ID的配置,保证跳转时会带上当前订单的order_id参数:
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="sales.order.info.links"> <block class="Magento\Sales\Block\Order\Link" name="sales.order.info.links.new.tab"> <arguments> <argument name="key" xsi:type="string">tab_new</argument> <argument name="path" xsi:type="string">subscription/index/index</argument> <argument name="label" xsi:type="string" translate="true">Tab Label</argument> <!-- 新增以下配置,自动拼接订单ID参数 --> <argument name="order" xsi:type="object">Magento\Sales\Model\Order</argument> </arguments> </block> </referenceBlock> </body> </page>
3. 自定义phtml获取订单信息(可选)
如果你的tab.phtml需要调用订单数据,建议将对应块的类替换为Magento\Sales\Block\Order\Info,就可以直接调用$block->getOrder()获取订单实例。修改subscription_index_index.xml中对应块的配置:
<referenceContainer name="content"> <block class="Magento\Sales\Block\Order\Info" name="tab_custom" template="Infopro_CustomSection::tab.phtml"/> </referenceContainer>
之后在tab.phtml中就可以正常调用订单方法,例如:
<?php $order = $block->getOrder(); ?> <p>订单号:<?= $order->getRealOrderId() ?></p> <p>下单时间:<?= $order->getCreatedAt() ?></p>
修改完成后执行bin/magento cache:clean清理缓存即可正常访问。
内容的提问来源于stack exchange,提问作者Soumyo Deepto
相关产品推荐
相关产品推荐

