5

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

3

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->addSuccess($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

  • 1
    Thanks a lot. Your solutions worked smoothly! – Sukeshini Mar 11 at 7:05
1

You can try with:

$message =  __('You added %1 to your shopping cart.', $product->getName()) . 
'<a  href="'. $customLinkHere .'">'. __('View Cart/Checkout') .'</a>';

See an sample here: \Magento\AdminNotification\Block\Grid\Renderer\Actions::render()

[EDIT] Change addSuccessMessage() to addSuccess()

[EDIT] 13 May 2018

We should try with addComplexSuccessMessage()

app/code/Vendor/Module/etc/frontend/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Controller\Cart\Add"
                type="Vendor\Module\Controller\Rewrite\Cart\Add" />

    <type name="Magento\Framework\View\Element\Message\MessageConfigurationsPool">
        <arguments>
            <argument name="configurationsMap" xsi:type="array">
                <item name="addCartSuccessMessage" xsi:type="array">
                    <item name="renderer" xsi:type="const">\Magento\Framework\View\Element\Message\Renderer\BlockRenderer::CODE</item>
                    <item name="data" xsi:type="array">
                        <item name="template" xsi:type="string">Vendor_Module::messages/addCartSuccessMessage.phtml</item>
                    </item>
                </item>
            </argument>
        </arguments>
    </type>
</config>

Vendor/Module/Controller/Rewrite/Cart/Add.php

<?php

namespace Vendor\Module\Controller\Rewrite\Cart;

class Add extends \Magento\Checkout\Controller\Cart\Add
{
    public function execute()
    {
        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        $params = $this->getRequest()->getParams();
        try {
            if (isset($params['qty'])) {
                $filter = new \Zend_Filter_LocalizedToNormalized(
                    ['locale' => $this->_objectManager->get(
                        \Magento\Framework\Locale\ResolverInterface::class
                    )->getLocale()]
                );
                $params['qty'] = $filter->filter($params['qty']);
            }
            $product = $this->_initProduct();
            $related = $this->getRequest()->getParam('related_product');
            /**
             * Check product availability
             */
            if (!$product) {
                return $this->goBack();
            }
            $this->cart->addProduct($product, $params);
            if (!empty($related)) {
                $this->cart->addProductsByIds(explode(',', $related));
            }
            $this->cart->save();
            /**
             * @todo remove wishlist observer \Magento\Wishlist\Observer\AddToCart
             */
            $this->_eventManager->dispatch(
                'checkout_cart_add_product_complete',
                ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
            );
            if (!$this->_checkoutSession->getNoCartRedirect(true)) {
                if (!$this->cart->getQuote()->getHasError()) {
                    if ($this->shouldRedirectToCart()) {
                        $message = __(
                            'You added %1 to your shopping cart.',
                            $product->getName()
                        );
                        $this->messageManager->addSuccessMessage($message);
                    } else {
                        $this->messageManager->addComplexSuccessMessage(
                            'addCartSuccessMessage',
                            [
                                'product_name' => $product->getName(),
                                'cart_url' => $this->getCartUrl(),
                            ]
                        );
                    }
                }
                return $this->goBack(null, $product);
            }
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            if ($this->_checkoutSession->getUseNotice(true)) {
                $this->messageManager->addNotice(
                    $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($e->getMessage())
                );
            } else {
                $messages = array_unique(explode("\n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->messageManager->addError(
                        $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($message)
                    );
                }
            }
            $url = $this->_checkoutSession->getRedirectUrl(true);
            if (!$url) {
                $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
            }
            return $this->goBack($url);
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now.'));
            $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
            return $this->goBack();
        }


    }

    /**
     * @return string
     */
    private function getCartUrl()
    {
        return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
    }
    /**
     * @return bool
     */
    private function shouldRedirectToCart()
    {
        return $this->_scopeConfig->isSetFlag(
            'checkout/cart/redirect_to_cart',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Vendor/Module/view/frontend/templates/messages/addCartSuccessMessage.phtml

<?php
// @codingStandardsIgnoreFile
/** @var \Magento\Framework\View\Element\Template $block */
?>

<?= $block->escapeHtml(__(
    'You added %1 to your <a href="%2">shopping cart</a>.',
    $block->getData('product_name'),
    $block->getData('cart_url')
), ['a']);

enter image description here

We can see this commit: https://github.com/magento/magento2/pull/13904/files#diff-1

  • Khoa TruongDinh@ when I use this then I am getting error message – sanjay May 11 '17 at 17:48
  • Khoa through showing error @ Undefined variable: customLinkHere in – sanjay May 11 '17 at 17:50
  • Khoa through @ please see the updated question – sanjay May 11 '17 at 18:01
  • @sanjay See my update answer: Change addSuccessMessage() to addSuccess(). – Khoa TruongDinh May 12 '17 at 11:17
  • OMG!! It works!! – zhartaunik Jun 30 '18 at 13:02
0

You need to override this file to achieve this.

vendor/magento/module-checkout/Controller/Cart/Add.php

You can override by creating a custom module at

app/code/Vendor/ModuleName/Controller/Cart/Add.php

and change this part of the code:

if (!$this->cart->getQuote()->getHasError()) {
                    $message = __(
                        'You added %1 to your shopping cart.',
                        $product->getName()
                    );
                    $this->messageManager->addSuccessMessage($message);
                }
  • Any other way , – sanjay May 11 '17 at 10:07
  • sejal @@ please see my updated question any idea , to print chekout url – sanjay May 11 '17 at 11:57
  • @sanjay which link you wish to add ? Product detail link or cart link? – Sejal Shah May 12 '17 at 5:57
0

I'm not sure why, but in my case, by calling the obsolete method without "Message" solves the issue with the links. Instead of using addNoticeMessage, I changed to addNotice, and the links were displayed.

In my case:

$noticeMsg = __('You must be <a href="%1">logged in</a> or <a href="%2">registered</a> to purchase these products.',
                        $this->_storeManager->getStore()->getUrl('customer/account/login'),
                        $this->_storeManager->getStore()->getUrl('customer/account/create')
                    );
$this->_messageManager->addNotice($noticeMsg);
0

That will a wrong way, you just want to add text to the message after product is added to cart thus you have to modify at the place from where text is coming:-

i.e, vendor\magento\module-checkout\Controller\Cart.php

On line 121

$message = __(
              'You added %1 to your shopping cart.',
              $product->getName()
             );

Modify above message as you want.

  • I have include this line or I have to replace this with any script – sanjay May 10 '17 at 13:07
  • You need to override the controller and replace the text, either by replacing the text or replacing $product->getName() with content you need – arushi May 10 '17 at 13:14
  • why we can not send a link with a varible pass in success function , see this updated question – sanjay May 11 '17 at 11:21
  • arushi Please see the error , I just updated question – sanjay May 11 '17 at 18:00
  • You need to review magento.stackexchange.com/questions/134702/… link for this, Here it has explained the same think how to add a link with success message. – arushi May 12 '17 at 6:31
0

My task is, add HTML link in out of stock product message in the cart page. I have done below changes to achieve this task.

1) Override validate function and modify the message with HTML message.

\Magento\CatalogInventory\Model\Quote\Item\QuantityValidator

2) Override ValidationMessages(module-checkout/Block/Cart/ValidationMessages.php) block addQuoteMessages method and remove escapeHtml from the setText method.

$message->setText($this->escapeHtml($message->getText()));

Replace with

$message->setText($message->getText());

3) Last thing you need to override the Observer with your custom module and change contruct method with custom module method Test\Module\Model\Quote\Item\QuantityValidator

Magento\CatalogInventory\Observer\QuantityValidatorObserver

Remove var/* generate/* and run setup:upgrade (if required then run static-content comment).

Hope the above code will help you.

Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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