13

Can I call Mage::getUrl() directly using $this-> in Magento2?

How can I use below code in Magento2?

$link = Mage::getUrl('*/*/*', array('_current'=>true, '_use_rewrite'=>true, '_query'=>$this_params));
2

3 Answers 3

21

In a block, you can use $this->getUrl() with the parameters as you know them from Magento 1. In a template, use $block->getUrl() instead.

Outside blocks and templates, you need access to \Magento\Framework\UrlInterface, so if it is not available yet in the current class, add it as a constructor parameter, assign it to $this->urlBuilder, then use $this->urlBuilder->getUrl().

2
  • 3
    before add it as a constructor parameter check if $context has already an accessible instance of urlBuilder.
    – LucScu
    Commented May 19, 2017 at 9:39
  • $context does have the urlInterface already. Should be able to do $this->_url->getUrl();
    – thindery
    Commented Dec 9, 2020 at 16:58
6

You can simply call this method in magento 2 using below way,

//define query array pass to url
    $query = ['str1' => 'value1', 'str2' => 'value2',];
    $link = $block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true, '_query' => $query]);

You can also pass action value instead of */*/* in above url, like 'customer/account/login' as per your required action.

0

You can use this in Magento 2 like

$block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true])
1
  • how to use it in Block file? i am trying to get another controller in backUrl function. Commented Aug 4, 2018 at 8:14

Your Answer

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

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