Component D7 Structure - uniqcle/Bitrix GitHub Wiki

Компонент D7

Stucture

Simple Component D7

<? if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

class testComponent extends CBitrixComponent{

    function var1() {
        $arResult['var1']  = 'Переменная var1 класса test';

        return $arResult;
    }

    public function executeComponent(){
        $this->arResult = array_merge($this->arResult, $this->var1());

        $this->includeComponentTemplate();
    }
}

Inheritance

<? if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

//Вызываем метод и класс, от которого будем наследоваться
CBitrixComponent::includeComponentClass('uniqcle:small_test_component');

class classComponentExtends extends testComponent{

    function var2(){
        $arResult['var2'] = 'Переменная var2 класса component.extends';

        return $arResult;
    }

    public function executeComponent()
    {
        $this->arResult = array_merge($this->arResult, $this->var2());

        parent::executeComponent();
    }
}

Example

index.php

Вызов компонента

<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle("");?>

<?
 $APPLICATION->IncludeComponent(
        "uniqcle:component.name", // разработчик:название компонента
        "",             // шаблон
        array(                    // параметры
                "CACHE_TIME" => 0,
                "CACHE_TYPE" => "A"
        )
  );
 ?>

<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php"); ?>
.description.php
<?
if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

$arComponentDescription = array(
    'NAME' => 'Хороший компонент',
    'DESCRIPTION' => 'Описание хорошего компонента',
    'ICON' => '',
    'CACHE_PATH' => 'Y',
    'SORT' => 10,
    'PATH' => array(
        'ID' => 'other',
        'NAME' => 'Решения UNIQCLE'
    )
);
.parameters.php
<? if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use Bitrix\Main\Loader;

if (!Loader::includeModule('iblock'))
    return;

$arTypes = CIBlockParameters::GetIBlockTypes(['-' => ' ']);

$arIBlocks = [];
if (
    isset($arCurrentValues['IBLOCK_TYPE'])
    && trim($arCurrentValues['IBLOCK_TYPE'])
    && trim($arCurrentValues['IBLOCK_TYPE']) != '-'
) {
    $rsIBlocks = CIBlock::GetList(
        ['SORT' => 'ASC'],
        ['SITE_ID' => $_REQUEST['site'], 'TYPE' => trim($arCurrentValues['IBLOCK_TYPE'])]
    );
    while ($arIBlock = $rsIBlocks->Fetch()) {
        $arIBlocks[$arIBlock['ID']] = '[' . $arIBlock['ID'] . '] ' . $arIBlock['NAME'];
    }
}

$arSections = [];
if (
    isset($arCurrentValues['IBLOCK_ID'])
    && intval($arCurrentValues['IBLOCK_ID']) > 0
) {
    $rsSections = CIBlockSection::GetList(
        [],
        ['IBLOCK_ID' => intval($arCurrentValues['IBLOCK_ID'])]
    );
    while ($arSection = $rsSections->Fetch()) {
        $arSections[$arSection['ID']] = '[' . $arSection['ID'] . '] ' . $arSection['NAME'];
    }
}


$arComponentParameters = [
    'GROUPS' => [
    ],
    'PARAMETERS' => [
        'CACHE_TIME' => [
            'DEFAULT' => '36001'
        ],
        'IBLOCK_TYPE' => [
            'PARENT' => 'BASE',
            'NAME' => 'Тип инфоблока',
            'TYPE' => 'LIST',
            'VALUES' => $arTypes,
            'DEFAULT' => 'offers',
            'REFRESH' => 'Y'
        ],
        'IBLOCK_ID' => [
            'PARENT' => 'BASE',
            'NAME' => 'Инфоблок',
            'TYPE' => 'LIST',
            'VALUES' => $arIBlocks,
            'DEFAULT' => '',
            'ADDITIONAL_VALUES' => 'Y',
            'REFRESH' => 'Y'
        ],
        'SECTION_ID' => [
            'PARENT' => 'BASE',
            'NAME' => 'Раздел инфоблока',
            'TYPE' => 'LIST',
            'VALUES' => $arSections,
            'DEFAULT' => '',
            'ADDITIONAL_VALUES' => 'Y',
            'REFRESH' => 'Y'
        ],
        'COUNT' => [
            'PARENT' => 'BASE',
            'NAME' => 'Количество',
            'TYPE' => 'STRING',
            'DEFAULT' => '1'
        ],

        'LIST_PARAM' => [
            'PARENT' => 'BASE',
            'NAME' => 'Список',
            'TYPE' => 'LIST',
            'MULTIPLE' => 'N',
            'VALUES' => array(5 => 'a', 6 => 'b', 7 => 'c'),
        ],

        'CHECKBOX_PARAM' => [
            'PARENT' => 'BASE',
            'NAME' => 'Галочка',
            'TYPE' => 'CHECKBOX',
            'DEFAULT' => 'N',
            'REFRESH' => 'Y',
        ],

        'FILE_PARAM' => [
            "PARENT" => "BASE_SETTINGS",
            "NAME" => 'Выберите файл:',
            "TYPE" => "FILE",
            "FD_TARGET" => "F",
            "FD_EXT" => 'wmv,wma,flv,vp6,mp3,mp4,aac,jpg,jpeg,gif,png',
            "FD_UPLOAD" => true,
            "FD_USE_MEDIALIB" => true,
            "FD_MEDIALIB_TYPES" => Array('video', 'sound')
         ],

        'COLOR_PICKER' => [
            "PARENT" => "BASE",
            "NAME" => 'Выбор цвета',
            "TYPE" => "COLORPICKER",
            "DEFAULT" => 'FFFF00'
        ],

        'STRING_PARAM' => [
            'PARENT' => 'BASE',
            'NAME' => 'Строка',
            'TYPE' => 'STRING',
            'DEFAULT' => '100',
            'COLS' => "3"
        ],

        'SLIDER_EFFECT' =>  array(
            'NAME'      =>  'Эффект смены слайдов',
            'TYPE'      =>  'LIST',
            'SORT'      =>  '10',
            'VALUES'    =>  array(
                'sliding'   =>  'Скольжение',
                'fading'    =>  'Затухание',
            ),
            'MULTIPLE'  =>  'N',
        ),
        'SLIDER_TIME'   =>  array(
            'NAME'      =>  'Скорочть смены слайдов (мс)',
            'TYPE'      =>  'STRING',
            'SORT'      =>  '20',
            'DEFAULT'   =>  '5000',
        ),


    ]
];
class.php
<? if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use Bitrix\Main\Loader,
    Bitrix\Iblock;

class FirstComponent extends CBitrixComponent {

    // Обработка параметров
    function onPrepareComponentParams($params){


        if ($params['CACHE_TYPE'] == 'Y' || $params['CACHE_TYPE'] == 'A') {
            $params['CACHE_TIME'] = intval($params['CACHE_TIME']);
        } else {
            $params['CACHE_TIME'] = 0;
        }

        #проверка входных параметров
        $params['IBLOCK_ID'] = isset($params['IBLOCK_ID']) && intval($params['IBLOCK_ID']) > 0 ? intval($params['IBLOCK_ID']) : 0;
        return $params;
    }

    public function executeComponent(){
        try {
            //StartResultCache return true, если кэш недействительный
            //StartResultCache return false и $arResult - если действителен

            if ($this->startResultCache(false)) {  //Берем из кэша или формируем заного результат, если нет кэша

                $this->checkModules();
                $this->prepareData();
                $this->doAction();

                $this->includeComponentTemplate();

            }
        } catch (Exception $e) {         //Если произошла к-л ошибка, выводим ошибку
            $this->AbortResultCache();
            $this->arResult['ERROR'] = $e->getMessage();
        }

    }

    protected function checkModules()
    {
        #подключаем нужные модули
        if (!Loader::includeModule('iblock'))
            throw new Exception('Модуль "Инфоблоки" не установлен');
    }

    protected function prepareData()
    {
        #проверки на существования
        $this->arResult['IBLOCK'] = [];
        if ($this->arParams['IBLOCK_ID']) {
            $this->arResult['IBLOCK'] = CIBlock::GetByID($this->arParams['IBLOCK_ID'])->Fetch();
        }
        if (!$this->arResult['IBLOCK']) {
            throw new Exception('Инфоблок не найден');
        }
    }

    protected function doAction()
    {
        $this->actionView();
    }

    protected function actionView()
    {
        $this->arResult['ITEMS'] = [];

        $rs = CIBlockElement::getList(
            ['rand' => 'asc'],
            ['IBLOCK_ID' => $this->arResult['IBLOCK']['ID'], 'SECTION_ID' => $this->arResult['SECTION']['ID']],
            false,
            ['nTopCount' => $this->arParams['COUNT']]
        );
        while ($ob = $rs->GetNextElement()) {
            $arItem = $ob->GetFields();
            $arItem['PROPERTIES'] = $ob->GetProperties();

            $arItem['DISPLAY_PROPERTIES'] = [];
            foreach ($arItem['PROPERTIES'] as $code => $arProp) {
                $prop = $arItem['PROPERTIES'][$code];
                if (
                    (is_array($prop['VALUE']) && count($prop['VALUE']))
                    || (!is_array($prop['VALUE']) && strlen($prop['VALUE']))
                ) {
                    $arItem['DISPLAY_PROPERTIES'][$code] = CIBlockFormatProperties::GetDisplayValue($arItem, $prop, 'app_banner');
                }
            }

            Iblock\Component\Tools::getFieldImageData(
                $arItem,
                ['PREVIEW_PICTURE', 'DETAIL_PICTURE'],
                Iblock\Component\Tools::IPROPERTY_ENTITY_ELEMENT,
                'IPROPERTY_VALUES'
            );

            $this->arResult['ITEMS'][] = $arItem;
        }

        if (!$this->arResult['ITEMS']) {
            $this->AbortResultCache();
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️