Ok, I finally can add the related_product
to the cart. In the code/core/Mage/Checkout/Model/Cart.php
file are two functions for adding products into the cart. The first is called public function addProduct($productInfo, $requestInfo=null)
, the second function is public function addProductsByIds($productIds)
.
The related_product
is added by id, the others are added with the addProduct()
function. The adding by id does not seem to work (at least for me it did not. Although magento used the unaltered Cart.php file from 1.7.0.2.
I solved this by altering the Cart.php file like this:
/**
* Add product to shopping cart (quote)
* This is the original function pasted from
* Mage/Checkout/Model/Cart.php line 245
* The function is working and adding products to the cart
*
* @param int|Mage_Catalog_Model_Product $productInfo
* @param mixed $requestInfo
* @return Mage_Checkout_Model_Cart
*/
public function addProduct($productInfo, $requestInfo=null)
{
$product = $this->_getProduct($productInfo);
$request = $this->_getProductRequest($requestInfo);
$productId = $product->getId();
if ($product->getStockItem()) {
$minimumQty = $product->getStockItem()->getMinSaleQty();
//If product was not found in cart and there is set minimal qty for it
if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty
&& !$this->getQuote()->hasProductId($productId)
){
$request->setQty($minimumQty);
}
}
if ($productId) {
try {
$result = $this->getQuote()->addProduct($product, $request);
} catch (Mage_Core_Exception $e) {
$this->getCheckoutSession()->setUseNotice(false);
$result = $e->getMessage();
}
/**
* String we can get if prepare process has error
*/
if (is_string($result)) {
$redirectUrl = ($product->hasOptionsValidationFail())
? $product->getUrlModel()->getUrl(
$product,
array('_query' => array('startcustomization' => 1))
)
: $product->getProductUrl();
$this->getCheckoutSession()->setRedirectUrl($redirectUrl);
if ($this->getCheckoutSession()->getUseNotice() === null) {
$this->getCheckoutSession()->setUseNotice(true);
}
Mage::throwException($result);
}
} else {
Mage::throwException(Mage::helper('checkout')->__('The product does not exist.'));
}
Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));
$this->getCheckoutSession()->setLastAddedProductId($productId);
return $this;
}
/**
* Adding products to cart by ids
* This function is the altered function, which works for me
* the edited lines are marked.
*
* @param array $productIds
* @return Mage_Checkout_Model_Cart
*/
public function addProductsByIds($productIds)
{
$allAvailable = true;
$allAdded = true;
if (!empty($productIds)) {
foreach ($productIds as $productId) {
$productId = (int) $productId;
if (!$productId) {
continue;
}
$product = $this->_getProduct($productId);
if ($product->getId() && $product->isVisibleInCatalog()) {
try {
$this->getQuote()->addProduct($product);
} catch (Exception $e){
$allAdded = false;
}
/**
* START EDIT
*/
/**
* String we can get if prepare process has error
*/
if (is_string($result)) {
$redirectUrl = ($product->hasOptionsValidationFail())
? $product->getUrlModel()->getUrl(
$product,
array('_query' =>array ('startcustomization' => 1))
)
: $product->getProductUrl();
$this->getCheckoutSession()->setRedirectUrl($redirectUrl);
if ($this->getCheckoutSession()->getUseNotice() === null) {
$this->getCheckoutSession()->setUseNotice(true);
}
Mage::throwException($result);
}
Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));
$this->getCheckoutSession()->setLastAddedProductId($productId);
/**
* STOP EDIT
*/
} else {
$allAvailable = false;
}
}
if (!$allAvailable) {
$this->getCheckoutSession()->addError(
Mage::helper('checkout')->__('Some of the requested products are unavailable.')
);
}
if (!$allAdded) {
$this->getCheckoutSession()->addError(
Mage::helper('checkout')->__('Some of the requested products are not available in the desired quantity.')
);
}
}
return $this;
}
So i copied the lines from the other function. Does anyone think this will have some drawbacks? For me it looks like this introduces another check if everything works correct by examining the return string. But i don't know if dispatching the event might have some negative effects. As i stated, I'm new to magento and would like to know if this is solid solution.
Does anyone know, why the functions are different? Because they do basically the same. The only difference is, that the second function can add more than product. Maybe in this case dispatching the event is slow?
My suggestion would be to put an observer on the sales_quote_collect_totals_before
event which is fired in the Mage_Sales_Model_Quote::collectTotals
method before it starts the total collection process. Then from inside this observer method, iterate the quote items and change the tax class on the (already loaded) product object you can retrieve from the quote item.
After you set the information on the product object, whatever you do, DO NOT try and save it to the database. Having the tax class set as needed on the product object in memory will be good enough to have the collect totals logic found in Mage_Tax_Model_Sales_Total_Quote_Tax
pickup which tax class it should base it's calculations on. Saving the product (as you seem to be trying to do in your code sample above) will cause major performance issues, will create race conditions in the calculation process, and is simply not good practice.
The reason that the events you are trying to work with are not enabling you to accomplish what you are trying to accomplish is because they all come after the total calculation, a process which is only be run once prior to saving the quote.
Worth pointing out about the collect totals process is that once run, without doing extra work, you cannot call it again to have it re-calculate based on changes you've made to the quote items. See this tie-bit I've taken from the blog series a colleage of mine recently put together on the collect totals process:
Now that you understand what occurs during the totals collection
process, you may find it convenient or necessary to call it directly
yourself. Before you start feeling too confident with using
collectTotals for your own purposes, though, keep the following rule
in mind:
Products cannot be added to the quote after collectTotals is run!
. . . unless the quote addresses' item caches are cleared.
Nearly every total model's "collect" method relies on fetching the
quote items from the address and looping through them. The first time
getAllItems is run on a quote address, the item collection is actually
cached with a unique key, and it's this cached collection that is
returned on subsequent calls.
If you do happen to have an inkling for really diving into the depths of how the collect totals process works, you can check out the first of the four part series on total collection here for more in-depth reading: Unravelling Magento's collectTotals: Introduction
To summarize, you need to be catching an event which runs before the collect totals process (and before getAllItems is called on the quote addresses) so that changes you make to the items will be used by the total collectors. I've not verified that the suggested sales_quote_collect_totals_before
event runs before any calls to the getAllItems
on the quote address, but I'm almost certain that it will work for what you need. But if not, hopefully I've provided enough context for you to figure out which event you need to catch to make it work.
Best Answer
You can just add an option to the product in the event
sales_quote_add_item
: