The question:
I want to know, how can I generate a valid admin url from
- A Controller
- 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.
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
From a controller you can simply use $this->getUrl('url/path/here', $paramsHere = array())
.
From anywhere else:
You need to add an instance of MagentoFrameworkUrlInterface
in your class and use that:
protected $urlBuider;
public function __construct(
....
MagentoFrameworkUrlInterface $urlBuilder,
....
) {
....
$this->urlBuilder = $urlBuilder;
....
}
Then you can use this:
$url = $this->urlBuilder->getUrl('url/path/here', $paramsHere = array());
Method 2
You can generate secure admin url key by
protected $urlBuider;
public function __construct(
....
MagentoBackendModelUrlInterface $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')])
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0