Magento | How can I add a product to a shopping cart in a user module?

I am currently working on creating a Cart control module on Magento 1.9

I am stuck in adding a product to my cart (I have tried many different things) and therefore I am turning to you for help.

My module extends the rest of the magento APIs, and I already managed to update my cart (number of products), but now I want to add a new product through the POST method. Of course, I am registered as a client. I have defined creation rights for this role. (I can do the update without any problems)

Here is my code:

protected function _create(array $data){ $store = $this->_getStore(); Mage::app()->setCurrentStore($store->getId()); $cart = Mage::getModel('checkout/cart'); $cart->init(); $productCollection = Mage::getModel('catalog/product')->load(4); // Add product to cart $cart->addProduct($productCollection, array( 'product_id' => $productCollection->getId(), 'qty' => '1' ) ); // Save cart $cart->save(); } 

In this simple example, I am trying to add product identifier 4 in the amount of 1. My problem is that I have no errors in the log and everything seems to be gone. But when I get my cart, there is no product to add ...

In response, I have the code 200 OK

Do you have any suggestions to help me?

Many thanks for your help

considers

+5
source share
1 answer

Finally I found a solution after traveling all over the internet;)

In fact, when you want to get to the cart before checking out, magento uses the definition of "Quote" ... It’s not easy to understand for a newbie to Magento .... Therefore, to facilitate the investigation of those who looked like me, there were problems, here is my code To add a new product to the cart (before checking):

 //$data['entity_id'] = The id of the product you want to add to the cart //$data['qty'] = The quantity you want to specify protected function _create(array $data) { $store = $this->_getStore(); Mage::app()->setCurrentStore($store->getId()); // Get Customer ID $customerID = $this->getApiUser()->getUserId(); // Load quote by Customer $quote = Mage::getModel('sales/quote') ->loadByCustomer($customerID); $product = Mage::getModel('catalog/product') // set the current store ID ->setStoreId(Mage::app()->getStore()->getId()) // load the product object ->load($data['entity_id']); // Add Product to Quote $quote->addProduct($product,$data['qty']); try { // Calculate the new Cart total and Save Quote $quote->collectTotals()->save(); } catch (Mage_Core_Exception $e) { $this->_error($e->getMessage(),Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR); } } 

Hope this helps someone.

Hi

Carniflex

+2
source

Source: https://habr.com/ru/post/1200921/


All Articles