How can I get cart products in a custom module plugin in magento 2 on before-save shipping info hear already i'm taking the customer address its working fine like this i need to get the cart products also
/app/code/Sem/Shipment/Plugin/Checkout/Model/ShippingInformationManagement.php
<?php
namespace Sem\Shipment\Plugin\Checkout\Model;
use Magento\Framework\Exception\StateException;
use Magento\Checkout\Model\Session;
class ShippingInformationManagement
{
protected $_messageManager;
protected $jsonResultFactory;
protected $_quote;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Quote\Model\QuoteFactory $quoteFactory
) {
$this->_messageManager = $messageManager;
$this->jsonResultFactory = $jsonResultFactory;
$this->_quote= $quoteFactory;
}
public function beforeSaveAddressInformation(
\Magento\Checkout\Model\ShippingInformationManagement $subject,
$cartId,
\Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
)
{
$cart = $this->_quote->create()->get($cartId);
$items = $cart->getAllVisibleItems();
$resulta = [];
if (count($items) > 0){
foreach ($items as $item)
$resulta[] = $item->getName();
}
//print_r($resulta);
$address = $addressInformation->getShippingAddress();
$postcode = $address->getData('postcode');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$result = $this->jsonResultFactory->create();
throw new StateException(__($resulta[0]));
}
}
Best Answer
I just assume you need to echo the product name only. If you need other fields, please let me know.
In your custom module PHP function: