How to get getUrl() In Plugin Or Observer File In Magento 2 ?

April 1, 2020
April 1, 2020 yogita khasturi

How to get getUrl() In Plugin Or Observer File In Magento 2 ?

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:

In plugin or Observer function you can get getUrl() as:

Run the below commands for getting the effect of our Dependency Injection code:

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.