Magento 2 – Getting Product Admin Area URL from Code

adminmagento2producturl

Inside an observer, I need to get the URL to edit the product in the Admin Area.

Using the following code :

$product->getUrlModel()->getUrl($product)

I get an URL which is not working (and it also have the session value)

http://magento.web/the_admin/catalog/product/view/id/1/s/joust-duffle-bag/key/53cdbf2e9e53cfd4950692664e643710ececac42a2d15156d531dde51454576f/

Which one is the best way to fetch the product URL of the Admin Area?

Best Answer

To get the Edit Product url (catalog/product/edit), you can use the Magento\Backend\Helper\Data::getUrl function.

Include it in your constructor:

public function __contruct(\Magento\Backend\Helper\Data $backendHelper)
{
    $this->backendHelper = $backendHelper;
}

Then call getUrl:

$productEditUrl = $this->backendHelper->getUrl(
    'catalog/product/edit',
    ['id' => 1]
);

This will get you the product edit url for the admin for the product with id 1.

Related Topic