M
M
Michael Kim2020-09-14 10:33:57
1C-Bitrix
Michael Kim, 2020-09-14 10:33:57

Is there a product in the Bitrix cart?

Given:
Editorial Online store + CRM.
All updates are current.

Task:
Check if the item exists in the cart.
Product type - SKU with 1 property added to cart.

I have code:

$obBasket = Basket::loadItemsForFUser(
  FUser::getId(),
  's3'
);

$productId = $_REQUEST['id'];
$obItem = $obBasket->getExistsItem('catalog', $productId, ['CODE' => 'PROP1', 'VALUE' => 'electron']);
var_dump($obItem); // null


There is definitely an item in the cart, but for some reason null is returned.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PetrPo, 2020-09-14
@devjob

Waiting for a beautiful solution from Bitrix? )) And here's the hell. To get your \Bitrix\Sale\BasketItem $obItem, you will have to pass all its $properties to the 3rd parameter of getExistsItem, like

$obItem = $obBasket->getExistsItem('catalog', $productId, [
  0 => ['CODE' => 'PROP1', 'VALUE' => 'electron'],
  //......
]);

it’s not at all clear why this method is public, if you use it, you need to know all the properties of the goods in the basket, it looked like this for me
$obItem = $obBasket->getExistsItem('catalog', $productId, [
  0 => ['CODE' => 'ARTNUMBER', 'VALUE' => '235-81-03'],
  1 => ['CODE' => 'COLOR_REF', 'VALUE' => 'Черный'],
  2 => ['CODE' => 'SIZES_CLOTHES', 'VALUE' => 'XS'],
  3 => ['CODE' => 'CATALOG.XML_ID', 'VALUE' => 'clothes_offers_s1'],
  4 => ['CODE' => 'PRODUCT.XML_ID', 'VALUE' => '332#337'],
]);

In general, the solution, of course, will not be as beautiful as just using the method, but if you look at the getExistsItem method, the same thing is done there, just something else
\Bitrix\Main\Loader::includeModule('sale');

$siteId = 's1';
$fUserId = \Bitrix\Sale\FUser::getId();
$productId = 139;
$productByBasketItem = null;
$bProductInBasket = false;

$basket = \Bitrix\Sale\Basket::loadItemsForFUser($fUserId, $siteId);
$basketItems = $basket->getBasketItems();

if($basketItems) {
  foreach($basketItems as $basketItem) {
    if($basketItem->getField('PRODUCT_ID') == $productId) {
      $productByBasketItem = $basketItem;
      $bProductInBasket = true;
      break;
    }
  }
}

var_dump($bProductInBasket);
var_dump($productByBasketItem);

In the example, I wrote a boolean $bProductInBasket and wrote the \Bitrix\Sale\BasketItem object itself into $productByBasketItem, choose according to the situation as you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question