1

I'm using Ajax for add products to cart programmatically, products added to the cart was fine and qty also, but the price was set to zero initially. After update the qty or add some other products from shop page, the item's price was changed as per the store.

What my code describes, Get custom attribute value for certain products from get request, based on that value find the original productId, to add the products to cart programmatically. Here is my controller code,

/**
 * @var \Magento\Checkout\Model\Session
 */
protected $checkoutSession;

/**
 * @var \Magento\Quote\Api\CartRepositoryInterface
 */
protected $cartRepository;

/**
 * @var \Magento\Catalog\Model\ProductFactory
 */
protected $productFactory;

protected $messageManager;

protected $_productCollectionFactory;

protected $stockItem;

/**
 * Addpack constructor.
 * 
 * @param \Magento\Framework\App\Action\Context $context
 * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
 * @param \Magento\Checkout\Model\Session $checkoutSession
 * @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
 * @param \Magento\Catalog\Model\ProductFactory $productFactory
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Framework\Message\ManagerInterface $messageManager,
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\CatalogInventory\Model\Stock\Item $stockItem
) {
    $this->resultPageFactory = $resultPageFactory;
    $this->checkoutSession = $checkoutSession;
    $this->cartRepository = $cartRepository;
    $this->productFactory = $productFactory;
    $this->messageManager = $messageManager;
    $this->_productCollectionFactory = $productCollectionFactory;
    $this->stockItem = $stockItem;

    parent::__construct($context);
}
public function execute()
{
    try {

        $productId_array = $this->getRequest()->getParam('rec_genric_cat');
        if(!empty($productId_array)){
        // var_dump($productId_array);
        // exit();
        $quote = $this->checkoutSession->getQuote();
        //echo "";print_r($postedData['multi_add']);exit;
        $prod_out_stock = [];
        foreach ($productId_array as $productId) {

            $split_prod_value = explode('$$', $productId);
            $findedproductId = $split_prod_value[0];
            $getprod_gen_category = $split_prod_value[1];

            $totawid = [];
            $totcollection = $this->_productCollectionFactory->create();
            $totcollection->addAttributeToSelect('*');
            $totcollection->toArray();
            foreach($totcollection as $row){
                $totawid[] = $row['aw_product_id'];
            }

            if(in_array($findedproductId, $totawid)){
            $collection = $this->_productCollectionFactory->create();
            $collection->addAttributeToSelect('*');
            $collection->addAttributeToFilter('aw_product_id', $findedproductId);
            //$collection->setPageSize(3); // fetching only 3 products
            $prod_data = $collection->toArray();
            foreach($prod_data as $row){
                $getproductId = $row['entity_id'];
                //$getprod_gen_category = $row['aw_product_id'];
            }
            $product = $this->productFactory->create()->load($getproductId);

            $stockItem = $this->stockItem->load($product->getId(), 'product_id');
            $prod_qty = $stockItem->getQty();

            if($prod_qty > 0){
                $requestInfo = [
                    'qty' => 1
                ];
                $request = new \Magento\Framework\DataObject($requestInfo);
                // $quote->addProduct($product, $request);
                if ($product->getId()) {
                    $quote->addProduct($product, $request);
                }
            }else{
                $prod_out_stock[] = $getprod_gen_category;
            }
        }//inarray if end
        else{
            $prod_out_stock[] = $getprod_gen_category;
        }

        }

        $this->cartRepository->save($quote);
        $this->checkoutSession->replaceQuote($quote)->unsLastRealOrderId();

        $tot_prod_checked_count = count($productId_array);
        $tot_prod_out_stock = count($prod_out_stock);
        if($tot_prod_out_stock == 0){

            //success
            $response = $this->resultFactory
            ->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
            ->setData([
            'status' => 'success',    
            'url' => $this->_url->getUrl('checkout/cart'),
            'tag' => ''
            ]);
            return $response;

        }
    }
    } catch (\Magento\Framework\Exception\LocalizedException $e) {
        $this->messageManager->addException(
            $e,
            __('%1', $e->getMessage())
        );
    } catch (\Exception $e) {
        $this->messageManager->addException($e, __('error.'));
    }
    /*cart page*/

    //$this->getResponse()->setRedirect('/checkout/cart/index');


}

}

I'm also tried the sections.xml and events.xml for this logic, but no progress. kindly guide me for further development.

  • first, add product after running below command php -dmemory_limit=-1 bin/magento indexer:reindex – Vishal Baraiya Dec 6 '19 at 5:32
  • @VishalBaraiya thanks for your response and i will note down this command for future issues. Now i changed my controller code and perfectly works now, basde on this link magento.stackexchange.com/questions/286185/… – Manoj R Dec 6 '19 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.