Is there a way to somehow take the existing quote and create a new one identical to it but with a new ID?
This is what I currently have:
Updated following suggestions from @Vishwas:
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Quote\Model\QuoteRepository;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\ProductFactory;
class ShareCart extends \Magento\Framework\App\Action\Action
{
protected $resultFactory;
protected $storeManager;
protected $quoteFactory;
protected $transportBuilder;
protected $stateInterface;
protected $cart;
protected $productFactory;
public function __construct(
Context $context,
ResultFactory $resultFactory,
StoreManagerInterface $storeManager,
QuoteRepository $quoteFactory,
TransportBuilder $transportBuilder,
StateInterface $stateInterface,
Cart $cart,
ProductFactory $productFactory
) {
$this->resultFactory = $resultFactory;
$this->storeManager = $storeManager;
$this->quoteFactory = $quoteFactory;
$this->transportBuilder = $transportBuilder;
$this->stateInterface = $stateInterface;
$this->cart = $cart;
$this->productFactory = $productFactory;
parent::__construct($context);
}
public function execute()
{
try
{
$post = (array) $this->getRequest()->getPost();
$id = $this->cart->getQuote()->getId();
if ($id > 0) {
$quote = $this->quoteFactory->get($id);
$items = $quote->getAllVisibleItems();
foreach ($items as $item) {
$productId = $item->getProductId();
$_product = $this->productFactory->create()->load($productId);
$options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
$info = $options['info_buyRequest'];
$request1 = new \Magento\Framework\DataObject();
$request1->setData($info);
$this->cart->addProduct($_product, $request1);
}
$this->cart->save();
// Retrieve form data
$email = $post['basketshare-email'];
$message = $post['basketshare-message'];
$from_name = "";
}
} catch (\Exception $e) {
$this->messageManager->addError(__($e->getMessage()));
}
}
}
UPDATE:
$this->cart->addProduct($product, $request);
}
// save the updated cart items then re-attach the cart to the original quote
$this->cart->save();
$this->cart->setQuote($quote);
$this->checkoutSession->setQuoteId($quote->getId());
$this->cart->save();
I think there is something I'm not doing right here but I'm struggling to find any help on Google at the moment :)