How to Create Custom Error Message in Magento 2 Cart

cartexceptionmagento2

I am trying to create custom validation for products in the Magento 2 cart.

I have created a plugin:

<type name="Magento\Checkout\Controller\Index\Index">
    <plugin name="checkQuantityGroups"
            type="Wildcard\QuantityGroups\Plugin\CheckoutIndexPlugin"
            sortOrder="0"/>
</type>

With the following code:

public function beforeExecute()
{
    // Get quote from session

    /** @var Quote $quote */
    $quote = $this->checkoutSession->getQuote();

    // Get items in quote
    $cartItems = $quote->getAllItems();

    $quantityGroupsInCart = [];

    /** @var Quote\Item $item */
    foreach ($cartItems as $item) {
        $productId            = $item->getProductId();
        $product              = $this->productRepository->getById($productId);
        $productQuantityGroup = $product->getQuantityGroup();

        if ($product->getTypeId() == Configurable::TYPE_CODE) {
            continue;
        }

        $quantityGroupsInCart[$productQuantityGroup][] = $productId;
    }

    foreach ($quantityGroupsInCart as $quantityGroupId => $quantityGroupProducts) {
        // Get number allowed for QG
        $quantityGroup = $this->quantityGroup->load($quantityGroupId);

        $minAllowed = $quantityGroup->getNumberAllowed();

        if (count($quantityGroupProducts) < $minAllowed) {
            throw new LocalizedException(__("You need to add more {$quantityGroup->getTitle()}"));
        }
    }
}

I am using LocalizedException as I don't know what else to use. All this exception does is show the message and stack trace.

Can someone please let me know what I can use to show a styled error message in the cart instead?

Best Answer

You can use ManagerInterface for display message in magento 2

..........
protected $_messageManager;

public function __construct(
    \Magento\Framework\Message\ManagerInterface $messageManager
) {
    $this->_messageManager = $messageManager;
}

public function yourmethod() {
    ..
    $message = 'You need to add more {$quantityGroup->getTitle()}';
    $this->_messageManager->addSuccess($message); //For Success Message
    $this->_messageManager->addError($message);//For Error Message
    ..
}
Related Topic