1. Define the Layout Update XML
In Magento 2, layout files are used to define the structure of the page. You will create a layout XML file to add your custom section to the order view page.
- Create a layout file:
view/adminhtml/layout/sales_order_view.xml
in your custom module.
<?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="order_info">
<block class="Vendor\Module\Block\Adminhtml\Order\View\Custom" name="custom.order.info.block" template="Vendor_Module::order/view/custom.phtml" />
</referenceBlock>
</body>
</page>
In this example:
order_info
is the block name to which you are adding your custom block.
Vendor\Module\Block\Adminhtml\Order\View\Custom
is the class that will handle the custom block's logic.
custom.order.info.block
is the name of the custom block.
Vendor_Module::order/view/custom.phtml
is the template file for your custom section.
2. Create the Block Class
Create the block class Custom.php
that will provide the necessary data to your template.
- Path:
Vendor/Module/Block/Adminhtml/Order/View/Custom.php
<?php
namespace Vendor\Module\Block\Adminhtml\Order\View;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Api\OrderRepositoryInterface;
class Custom extends Template
{
protected $orderRepository;
public function __construct(
Template\Context $context,
OrderRepositoryInterface $orderRepository,
array $data = []
) {
$this->orderRepository = $orderRepository;
parent::__construct($context, $data);
}
public function getOrder()
{
$orderId = $this->getRequest()->getParam('order_id');
return $this->orderRepository->get($orderId);
}
public function getCustomData()
{
// Your logic to get custom data for the order
return 'Custom Data';
}
}
3. Create the Template File
Create the template file custom.phtml
where you will define the HTML and PHP code to display the custom data.
- Path:
Vendor/Module/view/adminhtml/templates/order/view/custom.phtml
<?php
$order = $block->getOrder();
$customData = $block->getCustomData();
?>
<div class="custom-order-section">
<h3>Custom Order Section</h3>
<p>Order ID: <?= $order->getEntityId(); ?></p>
<p>Custom Data: <?= $customData; ?></p>
</div>
4. Run Upgrade and Clear Cache
Finally, run the Magento upgrade and clear the cache:
php bin/magento setup:upgrade
php bin/magento cache:clean
php bin/magento cache:flush
Please let me know if you faced any issue