S
S
Sergey2018-10-31 22:36:50
1C-Bitrix
Sergey, 2018-10-31 22:36:50

How to add a product to the cart when adding another product?

Hello colleagues!
After update 18.1.3, Add2BasketByProductID does not seem to work.
For certain products, you need to add another previously known product to the cart.
On the OnBeforeBasketAdd event, I use the Add2BasketByProductID method to add a product.

AddEventHandler("sale", "OnBeforeBasketAdd", Array("CSaleHandlers","OnBeforeBasketAddHandler") );

class CSaleHandlers{
   function OnBeforeBasketAddHandler(&$arFields) {
      $arID = array(896,897,898,899,900,901,902,903,904,906,1457,1458);
      if( in_array($arFields["PRODUCT_ID"], $arID) ){
         $pos = Add2BasketByProductID( 1027, 2, array(), array() );
         AddMessage2Log('$pos = '.print_r($pos, true),'');
      }
   }
}

As a result, I get the item position code in the cart in $pos, that is, the method worked, there is no error. But there is no item in the cart.
If the product with PRODUCT_ID = 1027 is already in the cart, then the method successfully adds the specified quantity of 2 pcs to it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2018-11-03
@SirBataneg

Evgeny Zhukov on the forum helped to solve this issue by advising to use the \Bitrix\Catalog\Product\Basket::addProduct method (for public components) and \Bitrix\Catalog\Product\Basket::addProductToBasket (for arbitrary, including administrative scripts)."

R
Roman Gritsuk, 2018-10-31
@winer

After function Add2BasketByProductID try to add

if ($ex = $APPLICATION->GetException()){
     \Bitrix\Main\Diag\Debug::dumpToFile($ex->GetString());
}

You can try adding an item to your cart like this:
$product = array(
    'PRODUCT_ID' => $productId,
    'QUANTITY' => $quantity
);
/*@var $basketResult Bitrix\Main\Result*/
$basketResult = Catalog\Product\Basket::addProduct($product);
if (!$basketResult->isSuccess()) {
    \Bitrix\Main\Diag\Debug::dumpToFile(implode('; ', $basketResult->getErrorMessages()));
}

logs from dumpToFile can be viewed in /__bx_log.log

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question