V
V
Vitaly2018-04-10 13:02:58
1C-Bitrix
Vitaly, 2018-04-10 13:02:58

How to randomize an element in catalog.section?

Essence of the question:
There are 20 items in the catalog on the page. It is necessary to display an advertising banner in a random place instead of one element (the "tile" catalog 4x5).
my solution:
Output in component template catalog.section
template.php

function randNumber() //вынес в init.php
  {
    return rand(1, 19);
  };
<?$i=1?>
<?foreach ($arResult['ITEMS'] as $arItem) :?>
  <article>/*контент*/</article>
  <? if(randNumber() == $i): ?>//проблема с кэшем
  <article>/*баннер $arResult["BANNER_LIST"]//проблема с кэшем*/</article>
  <? endif; ?>
<?$i++;?>
<?endforeach?>

Code in result_modifier.php
I get the bound element of the section, pass it to GetList, select one random element, save it to $arResult, feed it to the template
//Получаем баннер текущего раздела
$bannerItems = array();
$arSectionSelect = array("ID", "UF_BANNER");
$arSectionFilter = array("IBLOCK_ID"=>$arParams["IBLOCK_ID"], "ID"=>$arResult["ID"]);
$dbSectionList = CIBlockSection::GetList(array(), $arSectionFilter, false, $arSectionSelect);
while($arSection = $dbSectionList->GetNext()){
    $bannerItems = $arSection["UF_BANNER"];
};
$bannerList = array();
$arSelect = Array("ID", "NAME", "PREVIEW_PICTURE", "PROPERTY_NAME");
$arFilter = Array("IBLOCK_ID"=>23, "ACTIVE"=>"Y", "SECTION_ID"=>$bannerItems, 'INCLUDE_SUBSECTIONS' =>'Y');
$res = CIBlockElement::GetList(array("RAND"=>"ASC"), $arFilter, false, Array ("nTopCount" => 1), $arSelect);
while($ob = $res->GetNextElement()){
    $arFields = $ob->GetFields();
    $bannerList = array(
      "NAME" => $arFields["NAME"],
      "BG" => $arFields["PREVIEW_PICTURE"],
      "DESCR" => $arFields["PROPERTY_NAME_VALUE"]
    );
};
//Сохраняем результат в кеш компонента
if($bannerList){
    $arResult["BANNER_LIST"] = $bannerList;
    $this->__component->setResultCacheKeys(array("BANNER_LIST"));
};

All this works fine ONLY with the cache turned off. Tell me how to make it work with the cache ???

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question