The default Magento 2 does not allow to call $this->getUrl() method in the plugin or observer file. However, web developers, have faced the scenarios where we need to go out of our way to fulfill the crazy client requirements!
You have to pass dependency as Magento\Framework\UrlInterface to construct() method when you require to call getUrl() function of Magento 2 in plugin or observer file.
Method to fetch getUrl() in plugin or observer file in Magento 2:
1 2 3 4 5 |
public function __construct( \Magento\Framework\UrlInterface $urlBuilder ) { $this->urlBuilder = $urlBuilder; } |
In plugin or Observer function you can get getUrl() as:
1 |
$this->urlBuilder->getUrl(‘sales/order/view’, [‘order_id’ => 1]); |
Run the below commands for getting the effect of our Dependency Injection code:
1 |
php bin/magento setup:di:compile |
Above url will return as:
http://{yoururl.com}/admin/sales/order/view/order_id/1/
That’s it.
Any questions on the subject? Don’t hesitate to specify them in the Comments section below. I’d be glad to support them.