При добавлении товара в корзину нужно сделать так, чтобы цена у товара изменялась на 10% (скидка 10%). То есть например товар стоит 200 руб. и нужно чтобы при добавлении товара в корзину товара падал бы в корзину уже с новой ценой, то есть 200 - 20 = 180 руб.
Погуглил cобытия - События Bitrix, попробовал это сделать используя событие OnBeforeBasketAdd - не получилось. Потом попробовал уже после добавления товара в корзину обновлять цену у нужного мне товара - вроде бы цена меняется, то вот выводится в корзине всё равно старая цена. Помогите кто может, вот код init.php:
Код
<?
//Надо написать обработчик для OnBeforeBasketAdd
use Bitrix\Sale;
//AddEventHandler("sale", "OnBeforeBasketAdd", Array("MyClass", "OnBeforeBasketAddCustom"));
AddEventHandler("sale", "OnBasketAdd", Array("MyClass", "OnBasketAddCustom"));
class MyClass
{
function OnBeforeBasketAddCustom(&$arFields)
{
$suffix = '_11_10_2021';
//получаем корзину для текущего юзера:
try{
dbgLog('test1', $suffix);
$basket = Sale\Basket::loadItemsForFUser(Sale\Fuser::getId(), Bitrix\Main\Context::getCurrent()->getSite());
//Информация о добавляемом товаре:
//dbgLog('Product_id: '.print_r($arFields['PRODUCT_ID'], true), $suffix);
//dbgLog('$arFields: '.print_r($arFields, true), $suffix);
//dbgLog('$product_info='.print_r($product_info, true), $suffix);
//Получение товаров в корзине, доступных для покупки (CAN_BUY=Y):
$orderBasket = $basket->getOrderableItems();
//dbgLog('$orderBasket='.print_r($orderBasket, true), $suffix);
$basketItems = $basket->getBasketItems(); // массив объектов Sale\BasketItem
foreach ($basketItems as $basketItem){
$price = $basketItem->getPrice();
dbgLog('$price='.print_r($price, true), $suffix);
//dbgLog('$basketItem NAME='.print_r($basketItem['NAME'], true), $suffix);
}
}catch(Exception $e){
dbgLog('error: '.$e,$suffix);
}
dbgLog('=============================================================================================',$suffix);
}
function OnBasketAddCustom($ID, $arFields)
{
$suffix = '_11_10_2021';
//dbgLog('Массив $arFields: '.print_r($arFields,true), $suffix);
dbgLog('test2', $suffix);
//dbgLog('$arFields='.print_r($arFields, true), $suffix);
$product_id = $arFields['PRODUCT_ID'];
$custom_price = $arFields['PRICE'] * 0.9;
$arFields['PRICE'] = $custom_price;
//dbgLog('$arFields НОВЫЙ='.print_r($arFields, true), $suffix);
//Товары в корзине
$basket = Sale\Basket::loadItemsForFUser(Sale\Fuser::getId(), Bitrix\Main\Context::getCurrent()->getSite());
$basketItems = $basket->getBasketItems(); // массив объектов Sale\BasketItem
foreach ($basket as $basketItem) {
dbgLog('price='.print_r($basketItem->getPrice(), true).' ID товара='.$basketItem->getProductId(),$suffix);
if($basketItem->getProductId()==$product_id){
dbgLog('Меняем цену у товара с ID='.$product_id,$suffix);
dbgLog('Старая цена: '.$basketItem->getPrice(), $suffix);
$basketItem->setField('PRICE', $custom_price); // Изменение поля
$basketItem->save();
/*$basketPropertyCollection = $basketItem->getPropertyCollection();
$basketPropertyCollection->getPropertyValues();
$basketPropertyCollection->setProperty(array(
array(
'NAME' => 'Цена',
'CODE' => 'PRICE',
'VALUE' => $custom_price,
'SORT' => 100,
),
));
$basketPropertyCollection->save();
*/
}
}
foreach ($basket as $basketItem){
if($basketItem->getProductId()==$product_id){
dbgLog('Обновленный товар с ID='.$basketItem->getProductId(),$suffix);
dbgLog($basketItem->getPrice(), $suffix);
}
}
//получаем корзину для текущего юзера:
//$basket = Sale\Basket::loadItemsForFUser(Sale\Fuser::getId(), Bitrix\Main\Context::getCurrent()->getSite());
//Информация о корзине (целиком о корзине):
/*$price = $basket->getPrice(); // Цена с учетом скидок
$fullPrice = $basket->getBasePrice(); // Цена без учета скидок
dbgLog('user_id='.Sale\Fuser::getId(), $suffix);
dbgLog('site_id='.Bitrix\Main\Context::getCurrent()->getSite(), $suffix);
dbgLog('$price='.$price, $suffix);
dbgLog('$fullPrice='.$fullPrice, $suffix);
$custom_price = $price * 0.9;
*/
dbgLog('=============================================================================================',$suffix);
}
}
?>
Не понимаю в чём дело. Функция dbgLog логирует данные в текстовый файл. Находится она тут: bitrix/modules/main/tools.php в самом конце. Очень мне помогает при отладке