Magento 2 – Get URL for Specific Store

geturlmagento2url

I need to render inside admin grid preview url for specific store (depends on which store is selected). In Magento 1 the code is this:

$storeId = (int)$this->getRequest()->getParam('store');
if ($storeId == 0) {
    $stores = Mage::app()->getStores(false, true);
    $storeId = current($stores)->getId();
}

$storeCode = Mage::app()->getStore($storeId)->getCode();        
$urlModel = Mage::getModel('core/url')->setStore($storeId);       
$url = $urlModel->getUrl(
    'banner/index/preview/id/'.$row->getId(), array(
        '_current' => false,
        '_query' => '___store='.$storeCode
   )
);

I ended up with this:

$storeId = (int)$this->request()->getParam('store');
if ($storeId == 0) {
    $stores = $storeManager->getStores(false);
    $storeId = current($stores)->getId();
}

$storeCode = $storeManager->getStore($storeId)->getCode();        

But I don't find any code snippet for Magento 2 to migrate $urlModel part of code from Magento 1.

Tnx for any idea.

Best Answer

inject storeManagerInterface in constructor

public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
   .....
) {
   ...
$this->_storeManager=$storeManager;
}

Now you can GetUrl by command

$this->_storeManager->getStore()->getUrl('routepath', ['_current' => true]);