3

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?

1 Answer 1

5

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
    ..
}
3
  • Awesome. Thank you. For bonus points, could you also let me know how to redirect back to the cart from the plugin to show the message? I have used return $this->resultRedirectFactory->create()->setPath('/checkout/cart'); but this doesn't work
    – Wildcard27
    May 1, 2017 at 5:36
  • Refer this answer for redirect from plugin magento.stackexchange.com/a/155270/35758 May 1, 2017 at 6:30
  • can we get the error message, like if i login with invalid details, some error message shows, how to get that message? Oct 25, 2018 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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