Skip to content

Get Custom Data in the observer to set in the quote

This is my custom controller :

<?php


namespace VednorModuleControllerCustomer;

use MagentoFrameworkControllerResultFactory;
use PsrLogLoggerInterface;

class Addtocart extends MagentoFrameworkAppActionAction
{
    protected $logger;
    /**
     * @var MagentoCheckoutModelCart
     */
    protected $cart;

    /**
     * @var MagentoCatalogModelProduct
     */
    protected $product;

    /**
     * @var MagentoFrameworkObjectManagerInterface
     */
    protected $_objectManager;

    protected $swatchesHelper;
    protected $resultFactory;

    /**
     * Addtocart constructor.
     * @param MagentoFrameworkAppActionContext $context
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param MagentoFrameworkViewResultPageFactory $resultPageFactory
     * @param MagentoCheckoutModelCart $cart
     * @param MagentoCatalogApiProductRepositoryInterface $productRepository
     * @param MagentoSwatchesHelperData $swatchesHelper
     */
    public function __construct(
        MagentoFrameworkAppActionContext           $context,
        MagentoStoreModelStoreManagerInterface      $storeManager,
        MagentoFrameworkViewResultPageFactory      $resultPageFactory,
        MagentoCheckoutModelCart                    $cart,
        MagentoCatalogApiProductRepositoryInterface $productRepository,
        MagentoFrameworkControllerResultFactory     $resultFactory,
        LoggerInterface                                 $logger,
        MagentoSwatchesHelperData                   $swatchesHelper
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->cart = $cart;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
        $this->swatchesHelper = $swatchesHelper;
        $this->resultFactory = $resultFactory;
        $this->logger = $logger;
        $this->_objectManager = $context->getObjectManager();
    }

    /**
     * @return MagentoFrameworkAppResponseInterface|MagentoFrameworkControllerResultInterface|void
     * @throws MagentoFrameworkExceptionLocalizedException
     * @throws MagentoFrameworkExceptionNoSuchEntityException
     */
    public function execute()
    {
        $productsData = $this->getRequest()->getParams();
        $unavailableProduct = [];
        $invalidSku = [];
        $cartValidate = false;
        $storeId = $this->storeManager->getStore()->getId();
        $totalItems = [];

        try {
            if ($this->getRequest()->getParam('form') === 'csv') {
                $uploader = $this->_objectManager->create(
                    'MagentoMediaStorageModelFileUploader',
                    ['fileId' => 'file']
                );
                $csvFile = $uploader->validateFile()['tmp_name'];

                // Parse CSV
                $csvData = array_map('str_getcsv', file($csvFile));
                $headers = array_map('trim', array_shift($csvData));
                foreach ($csvData as $row) {
                    $row = array_map('trim', $row);
                    if (count($headers) !== count($row)) {
                        continue; // Skip invalid rows
                    }
                    $rowData = array_combine($headers, $row);
                    if (!isset($rowData['sku'], $rowData['qty'], $rowData['ref'])) {
                        throw new MagentoFrameworkExceptionLocalizedException(
                            __('CSV must contain sku, qty, and ref columns.')
                        );
                    }
                    $totalItems[] = [
                        'sku' => $rowData['sku'],
                        'qty' => $rowData['qty'],
                        'ref' => $rowData['ref']
                    ];
                }
                $productsData['items'] = $totalItems;
            } else {
                $totalItems = $productsData['items'] ?? [];
            }

            $totalItemCount = count($totalItems);

            foreach ($totalItems as $productData) {
                if ($productData['qty'] > 0) {
                    $sku = trim($productData['sku']);
                    $Ref = $productData['ref'] ?? null;

                    // Check if product exists
                    if ($this->_objectManager->create('MagentoCatalogModelProduct')->getIdBySku($sku)) {
                        $_product = $this->productRepository->get($sku, false, null, true)
                            ->setData('store_id', $storeId);

                        $productData['product'] = $_product->getId();
                        $productAvailability = $this->_objectManager->create('VendorModuleHelperpro')
                            ->productIsAvailable($sku, $productData['qty']);
                        $productType = $_product->getTypeId();

                        // Handle product types and swatches
                        if ($productType == "configurable" && $this->swatchesHelper->isProductHasSwatch($_product)) {
                            $productData['super_attribute'] = $this->getRequest()->getParams()['super_attribute'][$_product->getId()];
                        }

                        if ($productAvailability['availability'] == 1) {
                            $productData['form_key'] = $productsData['form_key'];
                            $productData['options']['ref'] = $sRef;

                            $this->cart->addProduct($_product, $productData);
                            $cartValidate = true;
                        } else {
                            $unavailableProduct[] = $sku;
                        }
                    } else {
                        $invalidSku[] = $sku;
                    }
                }
            }

            $this->cart->save();
            $this->cart->setCartWasUpdated(true);

            // Existing success and error message handling
            // ...

        } catch (MagentoFrameworkExceptionLocalizedException $e) {
            $this->messageManager->addException($e, __('%1', $e->getMessage()));
        } catch (Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong. Please try again.'));
        }

        $redirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $redirect->setUrl('/orderbysku');
        return $redirect;
    }
}

On this point the cart is saved

            $this->cart->save();

But my this ref is not saving into the quote table.

I tried using this checkout_cart_save_before observer but the data is not getting.

I want to set this data into the quote also