Getting Order_ID in Custom Module for Magento 2 Admin
If you’re working on customizing the admin interface of your Magento 2 store, you might face challenges when trying to pass dynamic parameters like order_id to your custom module’s functions. This post will guide you through writing an order ID parameter in a custom module’s onclick function.
Understanding the Current Code
The provided code is a plugin for the ToolbarContext class of Magento 2. It aims to add a custom “review” button to the sales order view page in the admin panel:
public function beforePushButtons(
ToolbarContext $toolbar,
\Magento\Framework\View\Element\AbstractBlock $context,
\Magento\Backend\Block\Widget\Button\ButtonList $buttonList
) {
// ... existing code ...
$buttonList->add('order_review',
[
'label' => __('Custom Button'),
'onclick' => 'setLocation(\'/external_link.php?'.$id.'\')',
'class' => 'review'
]
);
}
However, there’s an issue with the onclick attribute of the “review” button. The $id variable is undefined in this context.
Resolving the Issue
To resolve this, you need to pass the order ID from the view page context to your plugin:
- Inject the current view page within your plugin class constructor:
use Magento\Sales\Block\Adminhtml\Order\View as OrderView;
public function __construct(
// ... existing dependencies ...
private readonly OrderView $viewPage,
)
{
// ... initialization code ...
}
- Update the
beforePushButtonsmethod to access the order ID:
public function beforePushButtons(
ToolbarContext $toolbar,
\Magento\Framework\View\Element\AbstractBlock $context,
\Magento\Backend\Block\Widget\Button\ButtonList $buttonList
) {
// ... existing code ...
if ($context instanceof OrderView) {
$orderId = (int)$context->getOrder()->getId();
} else {
return [$context, $buttonList];
}
$buttonList->add('order_review',
[
'label' => __('Custom Button'),
'onclick' => "setLocation('/external_link.php?order_id=$orderId')",
'class' => 'review'
]
);
return [$context, $buttonList];
}
- Now the
order_idparameter will be correctly set to the current order’s ID.
Conclusion
This post has demonstrated how to pass dynamic data like an order ID from a view page context to your custom plugin in Magento 2. By carefully managing dependencies and accessing the necessary methods, you can effectively customize the admin interface according to your needs.
Remember that working with plugins requires careful attention to the Magento core classes and a solid understanding of the framework’s architecture. For more detailed guides on Magento development, consider exploring Laravel Company’s blog on Magento 2.
Happy coding!