5

I have created a custom module for create the customer programmatically and add some products to that newly created customer's cart.

my code is working and products are also added to that customer's cart.But somehow the product prices are set to zero.

please check my code!!!

<?php
/**
 *
 * Copyright © 2015 Detailcommerce. All rights reserved.
 */
namespace Mp\Accountmanager\Controller\Accountmanager;

class Amsave extends \Magento\Framework\App\Action\Action
{
    protected $_messageManager;
    protected $cart;
    protected $product;
    protected $resultPageFactory;
    protected $customerRepositoryInterface;
    protected $quoteModel;
    protected $productRepository;
    protected $storeManager;

    public function __construct(
        \Magento\Framework\App\Action\Context $context, 
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
        \Magento\Quote\Model\Quote $quoteModel,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Catalog\Model\Product $product,
        \Magento\Checkout\Model\Cart $cart) {
        parent::__construct($context);
        $this->_messageManager = $messageManager;
        $this->storeManager = $storeManager;
        $this->resultPageFactory = $resultPageFactory;
        $this->cart = $cart;
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
        $this->quoteModel = $quoteModel;
        $this->productRepository = $productRepository;
        $this->product = $product;
    }
    public function execute()
    {
        $post = $this->getRequest()->getParams();

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
        $state = $objectManager->get('\Magento\Framework\App\State');

        $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');

        $websiteId = $storeManager->getWebsite()->getWebsiteId();

        $store = $storeManager->getStore();  // Get Store ID

        $storeId = $store->getStoreId();



            $customerSession = $objectManager->create('Magento\Customer\Model\Session');
            $customer_new = $customerFactory->create();

            $customer_new->setWebsiteId($websiteId);

            $customer_new->setEmail($post['customer_email']);

            $customer_new->setFirstname($post['customer_contact_person']);

            $customer_new->setLastname($post['customer_contact_person']);

            $customer_new->setPassword($post['customer_email']);

           $customer_new->save();



                                try {
                                $customer_id = $this->_customerRepositoryInterface->getById($customer_new->getId());
                                 $quote    = $this->quoteModel->loadByCustomer($customer_id);


                                if (!$quote->getId()) {
                                    $quote->setCustomer($customer_id);
                                    $quote->setIsActive(1);
                                    $quote->setStoreId($this->storeManager->getStore()->getId());
                                }

                                if($customerSession->getProcuctIdsSm() != NULL)
                                {
                                $products_array = $customerSession->getProcuctIdsSm();
                                $products_array = explode(',', $products_array);
                                }

                                //I got product array like $products_array = array (0,1,2,3). and it is correct.
                                foreach ($products_array as $value) 
                                 {
                                   // $product = $this->productRepository->getById($value);
                                    //$quote->addProduct($product, 1);

                                    $params = array(
                                    'product' => $value,
                                    'qty' => 2
                                );    
                                $_product = $this->productRepository->getById($value);    
                                $quote->addProduct($_product,1);    


                                 }
                                //  $quote->save();
                                  $quote->collectTotals()->save(); 

                                } catch (\Exception $e) {
                                    echo $e->getMessage(); die;
                                }


            $this->messageManager->addSuccessMessage(__("Thanks for filling form..."));


    $this->_redirect('checkout/cart');
}
}

Please see this image!!

enter image description here

please help me!!!! your effort would be appreciated... Thanks

Kushal Dani
  • 2,114
  • 2
  • 17
  • 49
Sunny Rahevar
  • 3,102
  • 1
  • 22
  • 42
  • I have the same problem but in my case, for a first product i can get the price and if i update the cart then i can see all the product price. – Jaimin Feb 27 '18 at 09:03
  • please try this may be it works for you. https://magento.stackexchange.com/questions/196578/how-to-add-product-to-cart-by-product-id-and-customer-id – Kushal Dani Feb 27 '18 at 10:06
  • @Kushal i have checked this link , but still i am facing the same issue. – Sunny Rahevar Feb 27 '18 at 13:42
  • @SunnyRahevar you can create 1 database in that you can same email address, a product is and status.when a customer is trying to log in at that time call observer. if in status you get 0. it means the first time a user is log in and at that time try to add product may be it work and change the status in that customer to 1. – Kushal Dani Feb 28 '18 at 04:50

1 Answers1

5

I got the solution by adding the extra interface and change in the add to cart code. Please see my beloved code to check the extra interface.

<?php
/**
 *
 * Copyright © 2015 Detailcommerce. All rights reserved.
 */
namespace Mp\Accountmanager\Controller\Accountmanager;

class Amsave extends \Magento\Framework\App\Action\Action
{
    protected $_messageManager;
    protected $cart;
    protected $product;
    protected $resultPageFactory;
    protected $customerRepositoryInterface;
    protected $quoteModel;
    protected $productRepository;
    protected $cartManagementInterface;
    protected $cartRepositoryInterface;
    protected $storeManager;

    public function __construct(
        \Magento\Framework\App\Action\Context $context, 
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
        \Magento\Quote\Model\Quote $quoteModel,
         \Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
         \Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Catalog\Model\Product $product,
        \Magento\Checkout\Model\Cart $cart) {
        parent::__construct($context);
        $this->_messageManager = $messageManager;
        $this->storeManager = $storeManager;
        $this->resultPageFactory = $resultPageFactory;
        $this->cart = $cart;
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
        $this->cartManagementInterface = $cartManagementInterface;
        $this->quoteModel = $quoteModel;
        $this->cartRepositoryInterface = $cartRepositoryInterface;
        $this->productRepository = $productRepository;
        $this->product = $product;
    }
    public function execute()
    {
        $post = $this->getRequest()->getParams();

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
        $state = $objectManager->get('\Magento\Framework\App\State');

        $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');

        $websiteId = $storeManager->getWebsite()->getWebsiteId();

        $store = $storeManager->getStore();  // Get Store ID

        $storeId = $store->getStoreId();


            $customerSession = $objectManager->create('Magento\Customer\Model\Session');
           $customer_new = $customerFactory->create();

            $customer_new->setWebsiteId($websiteId);

            $customer_new->setEmail($post['customer_email']);

            $customer_new->setFirstname($post['customer_contact_person']);

            $customer_new->setLastname($post['customer_contact_person']);

            $customer_new->setPassword($post['customer_email']);

           $customer_new->save();



                    $cartId = $this->cartManagementInterface->createEmptyCart(); //Create empty cart
                    $quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
                    $quote->setStoreId($this->storeManager->getStore()->getId());
                    $customer= $this->_customerRepositoryInterface->getById($customer_new->getId());
                    $quote->setCurrency();
                    $quote->assignCustomer($customer);

                    if($customerSession->getProcuctIdsSm() != NULL)
                    {
                    $products_array = $customerSession->getProcuctIdsSm();
                    $products_array = explode(',', $products_array);
                    }
                    $qty = 1;

                    foreach ($products_array as $value) 
                                 {
                        $params = array(
                        'product' => $value,
                        'qty' => $qty,
                        'price' => 15
                    );    
                    $_product = $this->productRepository->getById($value);    
                    $quote->addProduct($_product,$params);    

                                 }

                    $quote->collectTotals()->save();



            mail($to, $subject, $message, $headers);
            $this->messageManager->addSuccessMessage(__("Thanks for filling form..."));



    $this->_redirect('checkout/cart');
}
}
Sunny Rahevar
  • 3,102
  • 1
  • 22
  • 42
  • i am facing "We found an invalid request for adding product to quote.", while i pass the params i am getting this error. But if i set $quote->addProduct($_product,$qty); //qty =1, its working, so how can i set the custom price to the quote product – senthil Apr 30 '19 at 08:07
  • I have added the price parameter too in the code.Can you please try once and let me know does it works for you or not. – Sunny Rahevar Apr 30 '19 at 10:02