Magento – add link to the success message in Magento 2

addtocartmagento2

I am trying to add a product details link in the success message after a user clicks the add to cart button. So I create a variable in my controller but and want to send cart link. Here is file location vendor/magento/module-checkout/Controller/Cart

Here is some code from a similar question which was never solved. Can I include this with

if (!$this->_checkoutSession->getNoCartRedirect(true)) {
                if (!$this->cart->getQuote()->getHasError()) {
                  $cartLink = '<a href="'. $this->_url->getUrl('checkout/cart') .'">View Cart/Checkout</a>';
                   $message =  __('You added %1 to your shopping cart.', $product->getName()) . 
'<a  href="'.$cartLink .'">'. __('View Cart/Checkout') .'</a>';

                    $this->messageManager->addSuccessMessage($message);
                }

enter image description here

Best Answer

Try the below code in your controller its work for me

protected $_urlInterface;

public function __construct(
    \Magento\Framework\UrlInterface $urlInterface
) {
    $this->_urlInterface = $urlInterface;
    parent::__construct($context);
}

public function execute() {

$url = $this->_urlInterface->getUrl('checkout/cart', ['_secure' => true]);

    try{
        $message = __('You added '.$_product->getName().'to your <a href="'.$url.'">shopping cart.</a>');
        $this->messageManager->addSuccessMessage($message);
    } catch (\Exception $e) {
        $message = __("We don't have as many %1 as you requested.",$_product->getName());
                        $this->messageManager->addErrorMessage($message);
    }
}

The result should be like this See The Result Here

Related Topic