I created a module to add available qty to cart when customer request more than available qty. below is my code set.
app/code/E25media/MagentoCommunity/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">
<type name="Magento\Quote\Model\Quote">
<plugin name="sr_check_stock" type="E25media\MagentoCommunity\Plugin\Quote" sortOrder="1"/>
</type>
</config>
app/code/E25media/MagentoCommunity/Plugin/Quote.php
<?php
namespace E25media\MagentoCommunity\Plugin;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\DataObject\Factory as DataObjectFactory;
class Quote
{
/**
* @var StockRegistryInterface
*/
private $stockRegistry;
/**
* @var ManagerInterface
*/
private $messageManager;
/**
* @var DataObjectFactory
*/
private $objectFactory;
/**
* Quote constructor.
*
* @param StockRegistryInterface $stockRegistry
* @param ManagerInterface $messageManager
* @param DataObjectFactory $objectFactory
*/
public function __construct(
StockRegistryInterface $stockRegistry,
ManagerInterface $messageManager,
DataObjectFactory $objectFactory
) {
$this->stockRegistry = $stockRegistry;
$this->messageManager = $messageManager;
$this->objectFactory = $objectFactory;
}
public function beforeAddProduct(
\Magento\Quote\Model\Quote $subject,
\Magento\Catalog\Model\Product $product,
$request
) {
if ($request === null) {
$request = 1;
}
if (is_numeric($request)) {
$request = $this->objectFactory->create(['qty' => $request]);
}
$messageCollection = $this->messageManager->getMessages(true);
$messageCollection->getLastAddedMessage()->getText(); //Getting an error in this line.
if ($product->getId() && $request) {
$stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
if ($stockItem->getQty() < $request->getQty()) {
$remainingQty = $request->getQty() - $stockItem->getQty();
$request->setQty($stockItem->getQty());
$this->messageManager->addSuccess(__('%1 item not available', $remainingQty));
}
}
return [$product, $request];
}
}
as per requirement product is adding to the cart. I want to concatenate the message and add some more part to the message to show in the product profile page.
$messageCollection->getLastAddedMessage()->getText();
above line my code is breaking. Any help to complete my task higly apreciated