Skip to content

Generating URLs

ProcessEight edited this page Mar 24, 2021 · 3 revisions

Tested on Magento 2.3.5.

Generating a URL in the frontend

Example from core

To do

Custom example

To generate a frontend URL:

To generate a secure frontend URL:

To generate a secure frontend URL with secret key:

To generate a frontend URL with query parameters:

Generating a URL in the backend

\Magento\Backend\Model\UrlInterface is injected into \Magento\Backend\App\Action\Context. Any class which extends that (or injects it) can now access \Magento\Backend\Model\UrlInterface via the context object's method \Magento\Backend\App\Action\Context::getBackendUrl (getBackendUrl just returns the instance of \Magento\Backend\Model\UrlInterface injected into \Magento\Backend\App\Action\Context).

Route params

The second argument to \Magento\Backend\Model\Url::getUrl is an array which allows various settings to be passed:

  • _cache_secret_key: Determines whether the secret key should be cached
  • _fragment: A URL fragment, e.g. After the # sign in a URL.
  • _escape: Whether the URL should be returned escaped or not
  • _escape_params: Whether params in the URL should be escaped or not
  • _query: Query params which will be appended to the URL
  • _nosid: Whether the session ID query param should be appended to the URL (bool)
  • _current: Not sure what this does
  • _scope: The current store code
  • _scope_to_url: Whether the store code should be added to the URL (bool)
  • _use_rewrite: Whether to use an internal rewrite when generating a route
  • _direct: Something to do with internal redirects

Route params which are set in other modules:

  • id: Product ID. See \Magento\GoogleShoppingAds\Model\Indexer\PayloadGenerator\Attribute\AdditionalAttributes::getProductUrl()
  • s: URL Key. See \Magento\GoogleShoppingAds\Model\Indexer\PayloadGenerator\Attribute\AdditionalAttributes::getProductUrl()
  • category: Category ID: \Magento\Catalog\Model\Product\Url::getUrl()
  • in_cart: Used to redirect back to the cart if a product already exists in the cart and it is tried to be added again \Magento\Checkout\Helper\Cart::getAddUrl()

Example from core

\Magento\Captcha\Block\Adminhtml\Captcha\DefaultCaptcha::getRefreshUrl contains an example of using the dependency to generate a secure URL without a secret key:

    /**
     * Returns URL to controller action which returns new captcha image
     *
     * @return string
     */
    public function getRefreshUrl()
    {
        /** @var \Magento\Backend\Model\UrlInterface $this->_url */
        return $this->_url->getUrl(
            'adminhtml/refresh/refresh',
            ['_secure' => $this->_config->isSetFlag('web/secure/use_in_adminhtml'), '_nosecret' => true]
        );
    }

Custom examples

To generate a backend URL:

Generate the URL for the admin dashboard page:

/** @var \Magento\Backend\Model\UrlInterface $backendUrl */
$backendUrl = $bootstrap->getObjectManager()->create(\Magento\Backend\Model\UrlInterface::class);

$generatedUrl = $backendUrl->getUrl('adminhtml/dashboard/index');

var_dump($backendUrl); // string(130) "http://m23-example-modules.local/admin/admin/dashboard/index/key/7fc719bb562ca73ad72a45dc7ecde8c02140f7dc283d95ea59ee62594b5301c1/"

To generate a secure backend URL:

If config flag 'web/secure/use_in_adminhtml' is enabled, then this will return a URL generated using the secure base URL:

/** @var \Magento\Backend\Model\UrlInterface $backendUrl */
$backendUrl->getUrl(
    'adminhtml/refresh/refresh',
    ['_secure' => $this->_config->isSetFlag('web/secure/use_in_adminhtml'),]
);

var_dump($backendUrl); // string(130) "https://m23-example-modules.local/admin/admin/dashboard/index/key/7fc719bb562ca73ad72a45dc7ecde8c02140f7dc283d95ea59ee62594b5301c1/"

To generate a secure backend URL with secret key:

The secret key is automatically added to all backend URLs (it's called form_key in the code, which is a misnomer, because it's used in both forms and URLs).

To generate a backend URL without a secret key, pass the flag _nosecret:

/** @var \Magento\Backend\Model\UrlInterface $backendUrl */
$backendUrl->getUrl(
    'adminhtml/refresh/refresh',
    ['_nosecret' => true,]
);

To generate a backend URL with query parameters:

@todo

Points for further investigation

  • Why is there a specific class for generating backend URLs?
  • Are there other ways of generating URLs in the backend, or just the one referred to in the correct answer?
  • How is the backend frontname (i.e. /admin/) added to backend URLs?
  • How can you generate a URL with query parameters?

Copyright

© 2021 ProcessEight

Clone this wiki locally