Bitrix: кнопка добавить в корзину

Допустим вы решили создать свой шаблон для bitrix:catalog.section, все просто в цикле обрабатываете $arResult["ITEMS"] выводите то что вам необходимо. И конечно же необходима кнопка "добавить в корзину", зачем писать заново если битрикс сам уже умеет ajax-ом добавлять в корзину. Однако в шаблоне стандартного компонента сам черт ногу сломит и выдрать требуемый код не так уж просто. Далее я расскажу как прикрутить к своему шаблону битриксовское добавление товара.
Плюсы:
- не надо ничего писать самому.
- если у вас стандартная мини корзина (или правильно оформленный шаблон) то он будет сам обновляться.


1. Копируем выделенные файлы себе в шаблон (скрипты чтоб заработала привязка и ajax, папку перевода чтоб корректно отображать сообщения).

2. Считаем что у вас уже есть template.php в котором в цикле вывод товаров, обогащаем его данным для работы кнопки.
2.1 В цикле перед выводом элемента.

<?php
$strMainID = $this->GetEditAreaId($arItem['ID']);

$arItemIDs = array(
 'ID' => $strMainID,
 'PICT' => $strMainID.'_pict',
 'SECOND_PICT' => $strMainID.'_secondpict',
 'STICKER_ID' => $strMainID.'_sticker',
 'SECOND_STICKER_ID' => $strMainID.'_secondsticker',
 'QUANTITY' => $strMainID.'_quantity',
 'QUANTITY_DOWN' => $strMainID.'_quant_down',
 'QUANTITY_UP' => $strMainID.'_quant_up',
 'QUANTITY_MEASURE' => $strMainID.'_quant_measure',
 'BUY_LINK' => $strMainID.'_buy_link',
 'BASKET_ACTIONS' => $strMainID.'_basket_actions',
 'NOT_AVAILABLE_MESS' => $strMainID.'_not_avail',
 'SUBSCRIBE_LINK' => $strMainID.'_subscribe',
 'COMPARE_LINK' => $strMainID.'_compare_link',

 'PRICE' => $strMainID.'_price',
 'DSC_PERC' => $strMainID.'_dsc_perc',
 'SECOND_DSC_PERC' => $strMainID.'_second_dsc_perc',
 'PROP_DIV' => $strMainID.'_sku_tree',
 'PROP' => $strMainID.'_prop_',
 'DISPLAY_PROP_DIV' => $strMainID.'_sku_prop',
 'BASKET_PROP_DIV' => $strMainID.'_basket_prop',
);

$strObName = 'ob'.preg_replace("/[^a-zA-Z0-9_]/", "x", $strMainID);

$productTitle = (
 isset($arItem['IPROPERTY_VALUES']['ELEMENT_PAGE_TITLE'])&& $arItem['IPROPERTY_VALUES']['ELEMENT_PAGE_TITLE'] != ''
 ? $arItem['IPROPERTY_VALUES']['ELEMENT_PAGE_TITLE']
 : $arItem['NAME']
);

$minPrice = false;
if (isset($arItem['MIN_PRICE']) || isset($arItem['RATIO_PRICE'])) 
 $minPrice = (isset($arItem['RATIO_PRICE']) ? $arItem['RATIO_PRICE'] : $arItem['MIN_PRICE']);
?>

2.2 После вывода элемента.

<?
$emptyProductProperties = empty($arItem['PRODUCT_PROPERTIES']);
 
$arJSParams = array(
 'PRODUCT_TYPE' => $arItem['CATALOG_TYPE'],
 'SHOW_QUANTITY' => ($arParams['USE_PRODUCT_QUANTITY'] == 'Y'),
 'SHOW_ADD_BASKET_BTN' => false,
 'SHOW_BUY_BTN' => true,
 'SHOW_ABSENT' => true,
 'SHOW_OLD_PRICE' => ('Y' == $arParams['SHOW_OLD_PRICE']),
 'ADD_TO_BASKET_ACTION' => $arParams['ADD_TO_BASKET_ACTION'],
 'SHOW_CLOSE_POPUP' => ($arParams['SHOW_CLOSE_POPUP'] == 'Y'),
 'SHOW_DISCOUNT_PERCENT' => ('Y' == $arParams['SHOW_DISCOUNT_PERCENT']),
 'DISPLAY_COMPARE' => $arParams['DISPLAY_COMPARE'],
 'PRODUCT' => array(
  'ID' => $arItem['ID'],
  'NAME' => $productTitle,
  'PICT' => ('Y' == $arItem['SECOND_PICT'] ? $arItem['PREVIEW_PICTURE_SECOND'] : $arItem['PREVIEW_PICTURE']),
  'CAN_BUY' => $arItem["CAN_BUY"],
  'SUBSCRIPTION' => ('Y' == $arItem['CATALOG_SUBSCRIPTION']),
  'CHECK_QUANTITY' => $arItem['CHECK_QUANTITY'],
  'MAX_QUANTITY' => $arItem['CATALOG_QUANTITY'],
  'STEP_QUANTITY' => $arItem['CATALOG_MEASURE_RATIO'],
  'QUANTITY_FLOAT' => is_double($arItem['CATALOG_MEASURE_RATIO']),
  'SUBSCRIBE_URL' => $arItem['~SUBSCRIBE_URL'],
  'BASIS_PRICE' => $arItem['MIN_BASIS_PRICE']
 ),
 'BASKET' => array(
  'ADD_PROPS' => ('Y' == $arParams['ADD_PROPERTIES_TO_BASKET']),
  'QUANTITY' => $arParams['PRODUCT_QUANTITY_VARIABLE'],
  'PROPS' => $arParams['PRODUCT_PROPS_VARIABLE'],
  'EMPTY_PROPS' => $emptyProductProperties,
  'ADD_URL_TEMPLATE' => $arResult['~ADD_URL_TEMPLATE'],
  'BUY_URL_TEMPLATE' => $arResult['~BUY_URL_TEMPLATE']
 ),
 'VISUAL' => array(
  'ID' => $arItemIDs['ID'],
  'PICT_ID' => ('Y' == $arItem['SECOND_PICT'] ? $arItemIDs['SECOND_PICT'] : $arItemIDs['PICT']),
  'QUANTITY_ID' => $arItemIDs['QUANTITY'],
  'QUANTITY_UP_ID' => $arItemIDs['QUANTITY_UP'],
  'QUANTITY_DOWN_ID' => $arItemIDs['QUANTITY_DOWN'],
  'PRICE_ID' => $arItemIDs['PRICE'],
  'BUY_ID' => $arItemIDs['BUY_LINK'],
  'BASKET_PROP_DIV' => $arItemIDs['BASKET_PROP_DIV'],
  'BASKET_ACTIONS_ID' => $arItemIDs['BASKET_ACTIONS'],
  'NOT_AVAILABLE_MESS' => $arItemIDs['NOT_AVAILABLE_MESS'],
  'COMPARE_LINK_ID' => $arItemIDs['COMPARE_LINK'],
  'SUBSCRIBE_ID' => $arItemIDs['SUBSCRIBE_LINK'],
 ),
 'LAST_ELEMENT' => $arItem['LAST_ELEMENT']
);
unset($emptyProductProperties);
?>
<script type="text/javascript">
var <? echo $strObName; ?> = new JCCatalogSection(<? echo CUtil::PhpToJSObject($arJSParams, false, true); ?>);
</script>

2.3 После цикла для вывода сообщений.

<script type="text/javascript">
 BX.message({
  BTN_MESSAGE_BASKET_REDIRECT: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_BASKET_REDIRECT'); ?>',
  BASKET_URL: '<? echo $arParams["BASKET_URL"]; ?>',
  ADD_TO_BASKET_OK: '<? echo GetMessageJS('ADD_TO_BASKET_OK'); ?>',
  TITLE_ERROR: '<? echo GetMessageJS('CT_BCS_CATALOG_TITLE_ERROR') ?>',
  TITLE_BASKET_PROPS: '<? echo GetMessageJS('CT_BCS_CATALOG_TITLE_BASKET_PROPS') ?>',
  TITLE_SUCCESSFUL: '<? echo GetMessageJS('ADD_TO_BASKET_OK'); ?>',
  BASKET_UNKNOWN_ERROR: '<? echo GetMessageJS('CT_BCS_CATALOG_BASKET_UNKNOWN_ERROR') ?>',
  BTN_MESSAGE_SEND_PROPS: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_SEND_PROPS'); ?>',
  BTN_MESSAGE_CLOSE: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_CLOSE') ?>',
  BTN_MESSAGE_CLOSE_POPUP: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_CLOSE_POPUP'); ?>',
  COMPARE_MESSAGE_OK: '<? echo GetMessageJS('CT_BCS_CATALOG_MESS_COMPARE_OK') ?>',
  COMPARE_UNKNOWN_ERROR: '<? echo GetMessageJS('CT_BCS_CATALOG_MESS_COMPARE_UNKNOWN_ERROR') ?>',
  COMPARE_TITLE: '<? echo GetMessageJS('CT_BCS_CATALOG_MESS_COMPARE_TITLE') ?>',
  BTN_MESSAGE_COMPARE_REDIRECT: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_COMPARE_REDIRECT') ?>',
  SITE_ID: '<? echo SITE_ID; ?>'
 });
</script>

3. Важно в самом выводе элемента проставить id.

<div id="<?=$strMainID;?>">
 <a href="<?=$arItem["DETAIL_PAGE_URL"];?>" id="<?=$arItemIDs['PICT'];?>">
  <img src="<?=$arItem["PREVIEW_PICTURE"]["SRC"];?>" alt="<?=$productTitle;?>" />
 </a>
 <div id="<?=$arItemIDs['PRICE'];?>"><?=$minPrice['PRINT_VALUE'];?></div>
 <div id="<? echo $arItemIDs['BASKET_ACTIONS']; ?>">
  <a id="<? echo $arItemIDs['BUY_LINK']; ?>" href="javascript:void(0)" rel="nofollow">
   <span>
    Купить
   </span>
  </a>
 </div>
</div>

Что получится в целом:

<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
// print_r($arResult);
if (count($arResult["ITEMS"])):
?>

<?foreach($arResult["ITEMS"] as $arItem):
 $strMainID = $this->GetEditAreaId($arItem['ID']);

 $arItemIDs = array(
  'ID' => $strMainID,
  'PICT' => $strMainID.'_pict',
  'SECOND_PICT' => $strMainID.'_secondpict',
  'STICKER_ID' => $strMainID.'_sticker',
  'SECOND_STICKER_ID' => $strMainID.'_secondsticker',
  'QUANTITY' => $strMainID.'_quantity',
  'QUANTITY_DOWN' => $strMainID.'_quant_down',
  'QUANTITY_UP' => $strMainID.'_quant_up',
  'QUANTITY_MEASURE' => $strMainID.'_quant_measure',
  'BUY_LINK' => $strMainID.'_buy_link',
  'BASKET_ACTIONS' => $strMainID.'_basket_actions',
  'NOT_AVAILABLE_MESS' => $strMainID.'_not_avail',
  'SUBSCRIBE_LINK' => $strMainID.'_subscribe',
  'COMPARE_LINK' => $strMainID.'_compare_link',

  'PRICE' => $strMainID.'_price',
  'DSC_PERC' => $strMainID.'_dsc_perc',
  'SECOND_DSC_PERC' => $strMainID.'_second_dsc_perc',
  'PROP_DIV' => $strMainID.'_sku_tree',
  'PROP' => $strMainID.'_prop_',
  'DISPLAY_PROP_DIV' => $strMainID.'_sku_prop',
  'BASKET_PROP_DIV' => $strMainID.'_basket_prop',
 );

 $strObName = 'ob'.preg_replace("/[^a-zA-Z0-9_]/", "x", $strMainID);

 $productTitle = (
  isset($arItem['IPROPERTY_VALUES']['ELEMENT_PAGE_TITLE'])&& $arItem['IPROPERTY_VALUES']['ELEMENT_PAGE_TITLE'] != ''
  ? $arItem['IPROPERTY_VALUES']['ELEMENT_PAGE_TITLE']
  : $arItem['NAME']
 );

 $minPrice = false;
 if (isset($arItem['MIN_PRICE']) || isset($arItem['RATIO_PRICE'])) 
  $minPrice = (isset($arItem['RATIO_PRICE']) ? $arItem['RATIO_PRICE'] : $arItem['MIN_PRICE']);
 ?>
 <div id="<?=$strMainID;?>">
  <a href="<?=$arItem["DETAIL_PAGE_URL"];?>" id="<?=$arItemIDs['PICT'];?>">
   <img src="<?=$arItem["PREVIEW_PICTURE"]["SRC"];?>" alt="<?=$productTitle;?>" />
  </a>
  <div id="<?=$arItemIDs['PRICE'];?>"><?=$minPrice['PRINT_VALUE'];?></div>
  <div id="<? echo $arItemIDs['BASKET_ACTIONS']; ?>">
   <a id="<? echo $arItemIDs['BUY_LINK']; ?>" href="javascript:void(0)" rel="nofollow">
    <span>
     Купить
    </span>
   </a>
  </div>
 </div>
  <?
  $emptyProductProperties = empty($arItem['PRODUCT_PROPERTIES']);
   
  $arJSParams = array(
   'PRODUCT_TYPE' => $arItem['CATALOG_TYPE'],
   'SHOW_QUANTITY' => ($arParams['USE_PRODUCT_QUANTITY'] == 'Y'),
   'SHOW_ADD_BASKET_BTN' => false,
   'SHOW_BUY_BTN' => true,
   'SHOW_ABSENT' => true,
   'SHOW_OLD_PRICE' => ('Y' == $arParams['SHOW_OLD_PRICE']),
   'ADD_TO_BASKET_ACTION' => $arParams['ADD_TO_BASKET_ACTION'],
   'SHOW_CLOSE_POPUP' => ($arParams['SHOW_CLOSE_POPUP'] == 'Y'),
   'SHOW_DISCOUNT_PERCENT' => ('Y' == $arParams['SHOW_DISCOUNT_PERCENT']),
   'DISPLAY_COMPARE' => $arParams['DISPLAY_COMPARE'],
   'PRODUCT' => array(
    'ID' => $arItem['ID'],
    'NAME' => $productTitle,
    'PICT' => ('Y' == $arItem['SECOND_PICT'] ? $arItem['PREVIEW_PICTURE_SECOND'] : $arItem['PREVIEW_PICTURE']),
    'CAN_BUY' => $arItem["CAN_BUY"],
    'SUBSCRIPTION' => ('Y' == $arItem['CATALOG_SUBSCRIPTION']),
    'CHECK_QUANTITY' => $arItem['CHECK_QUANTITY'],
    'MAX_QUANTITY' => $arItem['CATALOG_QUANTITY'],
    'STEP_QUANTITY' => $arItem['CATALOG_MEASURE_RATIO'],
    'QUANTITY_FLOAT' => is_double($arItem['CATALOG_MEASURE_RATIO']),
    'SUBSCRIBE_URL' => $arItem['~SUBSCRIBE_URL'],
    'BASIS_PRICE' => $arItem['MIN_BASIS_PRICE']
   ),
   'BASKET' => array(
    'ADD_PROPS' => ('Y' == $arParams['ADD_PROPERTIES_TO_BASKET']),
    'QUANTITY' => $arParams['PRODUCT_QUANTITY_VARIABLE'],
    'PROPS' => $arParams['PRODUCT_PROPS_VARIABLE'],
    'EMPTY_PROPS' => $emptyProductProperties,
    'ADD_URL_TEMPLATE' => $arResult['~ADD_URL_TEMPLATE'],
    'BUY_URL_TEMPLATE' => $arResult['~BUY_URL_TEMPLATE']
   ),
   'VISUAL' => array(
    'ID' => $arItemIDs['ID'],
    'PICT_ID' => ('Y' == $arItem['SECOND_PICT'] ? $arItemIDs['SECOND_PICT'] : $arItemIDs['PICT']),
    'QUANTITY_ID' => $arItemIDs['QUANTITY'],
    'QUANTITY_UP_ID' => $arItemIDs['QUANTITY_UP'],
    'QUANTITY_DOWN_ID' => $arItemIDs['QUANTITY_DOWN'],
    'PRICE_ID' => $arItemIDs['PRICE'],
    'BUY_ID' => $arItemIDs['BUY_LINK'],
    'BASKET_PROP_DIV' => $arItemIDs['BASKET_PROP_DIV'],
    'BASKET_ACTIONS_ID' => $arItemIDs['BASKET_ACTIONS'],
    'NOT_AVAILABLE_MESS' => $arItemIDs['NOT_AVAILABLE_MESS'],
    'COMPARE_LINK_ID' => $arItemIDs['COMPARE_LINK'],
    'SUBSCRIBE_ID' => $arItemIDs['SUBSCRIBE_LINK'],
   ),
   'LAST_ELEMENT' => $arItem['LAST_ELEMENT']
  );
  unset($emptyProductProperties);
  ?>
  <script type="text/javascript">
  var <? echo $strObName; ?> = new JCCatalogSection(<? echo CUtil::PhpToJSObject($arJSParams, false, true); ?>);
  </script>
 </div>
<?endforeach;?>

<script type="text/javascript">
 BX.message({
  BTN_MESSAGE_BASKET_REDIRECT: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_BASKET_REDIRECT'); ?>',
  BASKET_URL: '<? echo $arParams["BASKET_URL"]; ?>',
  ADD_TO_BASKET_OK: '<? echo GetMessageJS('ADD_TO_BASKET_OK'); ?>',
  TITLE_ERROR: '<? echo GetMessageJS('CT_BCS_CATALOG_TITLE_ERROR') ?>',
  TITLE_BASKET_PROPS: '<? echo GetMessageJS('CT_BCS_CATALOG_TITLE_BASKET_PROPS') ?>',
  TITLE_SUCCESSFUL: '<? echo GetMessageJS('ADD_TO_BASKET_OK'); ?>',
  BASKET_UNKNOWN_ERROR: '<? echo GetMessageJS('CT_BCS_CATALOG_BASKET_UNKNOWN_ERROR') ?>',
  BTN_MESSAGE_SEND_PROPS: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_SEND_PROPS'); ?>',
  BTN_MESSAGE_CLOSE: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_CLOSE') ?>',
  BTN_MESSAGE_CLOSE_POPUP: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_CLOSE_POPUP'); ?>',
  COMPARE_MESSAGE_OK: '<? echo GetMessageJS('CT_BCS_CATALOG_MESS_COMPARE_OK') ?>',
  COMPARE_UNKNOWN_ERROR: '<? echo GetMessageJS('CT_BCS_CATALOG_MESS_COMPARE_UNKNOWN_ERROR') ?>',
  COMPARE_TITLE: '<? echo GetMessageJS('CT_BCS_CATALOG_MESS_COMPARE_TITLE') ?>',
  BTN_MESSAGE_COMPARE_REDIRECT: '<? echo GetMessageJS('CT_BCS_CATALOG_BTN_MESSAGE_COMPARE_REDIRECT') ?>',
  SITE_ID: '<? echo SITE_ID; ?>'
 });
</script>

<?endif;?>


Комментарии

Отправить комментарий

Популярные сообщения из этого блога

Google Chrome - видео в отдельном окне

Google chrome размытое изображение