cancel
Showing results for 
Search instead for 
Did you mean: 

Invalid method $cart->init();

SOLVED

Invalid method $cart->init();

I am updating Magento1 code to Magento2.
I am getting this error below for the line $cart->init();
Do I have to update this for Magento2?
Or is there something missing in my function?

 

 

Invalid method Magento\Checkout\Model\Cart\Interceptor::init

 

    protected function _reloadCart()
    {
        $currQuoteId = $this->_checkoutSession->getQuoteId(); 
       $this->_checkoutSession->unsetAll();
        $this->_checkoutSession->setQuoteId($currQuoteId);
        $cart = $this->cart;

        if ($cart->getQuote()->getItemsCount()) 
        {
            $cart->init();
            $cart->save();

            if (!$this->_getQuote()->validateMinimumAmount()) {
            //  $warning = Mage::getStoreConfig('sales/minimum_order/description');
             // $cart->getCheckoutSession()->addNotice($warning);
            } 
        }
    }
6 REPLIES

Re: Invalid method $cart->init();

You need to use reinitializeState() function for your magento 2 store.

 

In magento 1  public function init() useful for Initialize cart quote state to be able use it on cart page.

In Magento 2, protected function reinitializeState() used for Reinitialize cart quote state

You need to use,

$cart->reinitializeState()
If Issue Solved, Click Kudos/Accept As solutions.

Re: Invalid method $cart->init();

Hi, Thanks for the reply.

However I am receiving the error below:

Invalid method Magento\Checkout\Model\Cart\Interceptor::reinitializeState

Re: Invalid method $cart->init();

Receiving the same error.

Re: Invalid method $cart->init();

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Calculus\CustomOptions\Controller\Rewrite\Checkout\Cart;


use \Magento\Framework\Event\ObserverInterface;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\SerializerInterface;


class UpdatePost extends \Magento\Checkout\Controller\Cart
{

  /**
  * @var \Magento\Framework\Registry
  */
 
    protected $_registry;
    protected $eventManager;
    protected $_checkoutSession;
    protected $_logger;
    protected $_customerSession;
    protected $jsonResultFactory;
    protected $jsonHelper;
    protected $context;
    protected $resultFactory;
    protected $_resultPageFactory;
    protected $resultPage;
    protected $scopeConfig;
    private $resultJsonFactory;

    protected $request;
    protected $data;
    private $serializer;
    protected $_layout;

    public function _construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Event\Manager $eventManager,
        \Magento\Checkout\Model\Cart $cart,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Customer\Model\Session $customerSession,
        Context $context,
        array $data = [],
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        PageFactory $resultPageFactory,
       // \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        JsonFactory $resultJsonFactory,
       \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
       // PageFactory $resultPageFactory
       SerializerInterface $serializer,
       \Magento\Framework\View\LayoutInterface $layout
    ) {
        $this->_checkoutSession = $checkoutSession;
        $this->_registry = $registry;
        $this->eventManager = $eventManager;
        $this->cart = $cart;
        $this->_logger = $logger;
        $this->_customerSession = $customerSession;
        $this->context = $context;
        $this->jsonHelper = $jsonHelper;
       // $this->resultFactory = $resultFactory;
        $this->data = $data;
        $this->scopeConfig = $scopeConfig;
        $this->_resultPageFactory = $resultPageFactory;
        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context, $data);

       $this->serializer = $serializer;
       $this->_layout = $layout;
    }
    
    


  /**
     * Update shopping cart data action
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {

        $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->addInfo("execute");
          /** @var \Magento\Framework\Controller\Result\Json $resultJson */
      

        if (!$this->_formKeyValidator->validate($this->getRequest())) {
         //   return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
   
        $updateAction = (string)$this->getRequest()->getParam('update_cart_action');
    
        switch ($updateAction) {
            case 'empty_cart':
                $this->_emptyShoppingCart();
            break;
            case 'update_qty':
                $this->_updateShoppingCart();
            break;
            case 'update_ajax_options':     
            $this->_updateShoppingCart();
            return $this->_getTotalsHtml();
            break;     
            default:
            $this->_updateShoppingCart();
             
        }
        return $this->_goBack();
    }


      /**
     * Update customer's shopping cart
     *
     * @return void
     */
   protected function _emptyShoppingCart()
    {
        try {
            $this->cart->truncate()->save();
        } catch (\Magento\Framework\Exception\LocalizedException $exception) {
            $this->messageManager->addError($exception->getMessage());
        } catch (\Exception $exception) {
            $this->messageManager->addException($exception, __('We can\'t update the shopping cart.'));
        }
    }


/**
     * Update customer's shopping cart
     *
     * @return void
     */

 

    protected function _getCart()
    {
        return $this->cart->getQuote()->getItemsCollection();
    }
    
    protected function _getQuote()
    {
        return $this->cart->getQuote();
    }

 
    
    protected function _ajaxRedirectResponse()
    {
        $this->getResponse()
            ->setHeader('HTTP/1.1', '403 Session Expired')
            ->setHeader('Login-Required', 'true')
            ->sendResponse();
        return $this;
    }
    
    protected function _expireAjax()
    {
        if (!$this->_getQuote()->hasItems())
        {
            $this->_ajaxRedirectResponse();
            return true;
        }
        return false;
    }
    protected function _getTotalsHtml()
    {

        $response2 = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
        $layout = $response2->addHandle('checkout_cart_index')->getLayout();
        $response['cartcontent'] = $this->_view->getLayout()->getBlock('checkout.cart.form')->toHtml();
        $response['checkout_method'] = $this->_view->getLayout()->getBlock('checkout.cart.methods.bottom')->toHtml();
        $response['page_messages'] = $this->_view->getLayout()->getBlock('checkout.cart.validationmessages')->toHtml();
       // $response['cart_item'] = $this->_view->getLayout()->getBlock('checkout.cart.item')->toHtml();
        $response['content'] = $layout->renderNonCachedElement('checkout.cart.empty');
        $cartQuote= $this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
        $response['subtotaldata'] = $this->_objectManager->create('Magento\Checkout\Model\DefaultConfigProvider')->getConfig();    
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($response);
        
        
        $this->_checkoutSession->getQuote()->collectTotals()->save();
        
        return $resultJson;

    
}



protected function  _updateAjaxOptions(){



    $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->addInfo("_updateAjaxOptions");



    if ($this->getRequest()->isXmlHttpRequest() && $this->_expireAjax()) {
        return;
    }

     //fix for frontend cookies expired or missing
    /*if(!Mage::getModel('core/cookie')->get('frontend')) {
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode(array('totals' => $this->_getTotalsHtml()))); 
        return;
    }*/
    //fix end
       
    if ($this->getRequest()->isPost()) 
    {
    
        try { 
            
         

            $cartData = $this->getRequest()->getParam('cart');

            $this->_checkoutSession->setMyValue($cartData);
            $oldData = $cartData;


             if (is_array($cartData)) {
        
               $filter = new \Zend_Filter_LocalizedToNormalized(
                    ['locale' => $this->_objectManager->get('Magento\Framework\Locale\ResolverInterface')->getLocale()]
                );
         
             foreach ($cartData as $index => $data) {
                    if (isset($data['qty'])) {
                 
                    //    $cartData[$index]['qty'] = $filter->filter($data['qty']);
                    //   $oldData[$index]['qty'] = $this->_getQuote()->getItemById($index)->getQty();
                    }

                    if (isset($data['product_id'])) {
                        $cartData[$index]['cart_product_id'] = $data['product_id'];
                        $oldData[$index]['cart_product_id'] = $data['product_id'];
                    }   

                }
                   $cart = $this->cart;
                  if (! $cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) {
                    $this->_getQuote()->setCustomerId(null);
                }
           
              $cart->updateItems($cartData);
             $cart->save();

              // $this->_reloadCart();  
            } 



         /*   if ($this->_expireAjax()) {
                return;
            }
            */


           
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
           $cart->updateItems($oldData);
            $cart->save();
            $this->_getCart()->getCheckoutSession()->addError($e->getMessage()); 
        } catch (Exception $e) {  
            $this->messageManager->addException($e, __('We can\'t update the shopping cart.'));
            $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
        }

     //  $this->_registry->unregister('_singleton/cataloginventory/observer');
 

               
    }
    else
    {
       // $this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
    }


  
    return ;



}


/*
    protected function  _updateAjaxOptions(){



        $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->addInfo("_updateAjaxOptions");
        $this->_updateShoppingCart();
       
        return;
  


    }*/

    /**
     * Reload cart to display custom options correctly in AJAX response  
     */
    protected function _reloadCart()
    {

        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);

  
        $currQuoteId = $this->_checkoutSession->getQuoteId(); 
       $this->_checkoutSession->unsetAll();
        $this->_checkoutSession->setQuoteId($currQuoteId);
        $cart = $this->cart;

        if ($cart->getQuote()->getItemsCount()) 
        {
          //  $cart->reinitializeState();
            $cart->save();

            if (!$this->_getQuote()->validateMinimumAmount()) {
            //  $warning = Mage::getStoreConfig('sales/minimum_order/description');
             // $cart->getCheckoutSession()->addNotice($warning);
            } 
        }
    }
/**
     * Update customer's shopping cart
     *
     * @return void
     */
    protected function _updateShoppingCart()
    {

        $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->addInfo("_updateShoppingCart");
  
        try {
            $cartData = $this->getRequest()->getParam('cart');
   
            $this->_checkoutSession->setMyValue($cartData);

            if (is_array($cartData)) {
                $filter = new \Zend_Filter_LocalizedToNormalized(
                    ['locale' => $this->_objectManager->get(
                        \Magento\Framework\Locale\ResolverInterface::class
                    )->getLocale()]
                );
                foreach ($cartData as $index => $data) {
                    if (isset($data['qty'])) {
                        $cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
                    }
                }
                if (!$this->cart->getCustomerSession()->getCustomerId() && $this->cart->getQuote()->getCustomerId()) {
                    $this->cart->getQuote()->setCustomerId(null);
                }

                $cartData = $this->cart->suggestItemsQty($cartData);
                $this->cart->updateItems($cartData)->save();

                $this->_reloadCart();
           

                $this->_checkoutSession->setMyValue($cartData);
                
            }
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addError(
                $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($e->getMessage())
            );

        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('We can\'t update the shopping cart.'));
            $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
   
        }
    
    }


    
  
}

Re: Invalid method $cart->init();

You dont need to reinitializeState() funciton in  your code, after calling save()  function of Model Cart class,

 

reinitializeState() already called inside save function.

 

You just need to do like in your code,

if ($cart->getQuote()->getItemsCount()) 
{
$cart->save();

if (!$this->_getQuote()->validateMinimumAmount()) {
// $warning = Mage::getStoreConfig('sales/minimum_order/description');
// $cart->getCheckoutSession()->addNotice($warning);
} 
}

Because save function in Magento/Checkout/Model/Cart with function like, already call reinitializeState() function.

/**
     * Save cart
     *
     * @return $this
     */
    public function save()
    {
        $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);

        $this->getQuote()->getBillingAddress();
        $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
        $this->getQuote()->collectTotals();
        $this->quoteRepository->save($this->getQuote());
        $this->_checkoutSession->setQuoteId($this->getQuote()->getId());
        /**
         * Cart save usually called after changes with cart items.
         */
        $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
        $this->reinitializeState();
        return $this;
    }

 

If Issue Solved, Click Kudos/Accept As solutions.

Re: Invalid method $cart->init();

Thank you.