10

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.

asked Mar 1, 2016 at 9:00

2 Answers 2

19

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());
answered Mar 1, 2016 at 9:07
2
  • 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! Commented Oct 10, 2016 at 10:08
  • Yep. This has changed. You are right. Commented Oct 10, 2016 at 14:43
2

You can generate secure admin url key by

protected $urlBuider;
public function __construct(
 ....
 \Magento\Backend\Model\UrlInterface $urlBuilder,
 ....
) {
 ....
 $this->urlBuilder = $urlBuilder;
 ....
}
public function Yourmethod()
{
$this->urlBuilder->getRouteUrl('RouteId/ControllerName/actionName',[ 'key'=>$this->urlBuilder->getSecretKey('RouteId','ControllerName','actionName')])
}

If you want to send parameters then add your params before key

$this->urlBuilder->getRouteUrl('RouteId/ControllerName/actionName',[ 'param1'=> 'paramValue1','param2'=> 'paramValue2','key'=>$this->urlBuilder->getSecretKey('RouteId','ControllerName','actionName')])
answered Nov 29, 2019 at 11:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.