I want to know, how can I generate a valid admin url from

  1. A Controller
  2. Anywhnere

so I can make any custom url admin work if I need it in an ajax or whatever. Answer for either 1 or 2 will do the job, bot I think it is better to have both.


From a controller you can simply use $this->getUrl('url/path/here', $paramsHere = array()).

From anywhere else:

You need to add an instance of \Magento\Framework\UrlInterface in your class and use that:

protected $urlBuider;
public function __construct(
    \Magento\Framework\UrlInterface $urlBuilder,
) {
    $this->urlBuilder = $urlBuilder;

Then you can use this:

$url = $this->urlBuilder->getUrl('url/path/here', $paramsHere = array());
  • 1
    In Magento 2.0.6 getUrl() is defined in \Magento\Framework\UrlInterface not (or no longer or not yet) in \Magento\Backend\Model\UrlInterface! – fietserwin Oct 10 '16 at 10:08
  • Yep. This has changed. You are right. – Marius Oct 10 '16 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.