Пример вывода списка с фильтром и сортировкой в админке 1С-Битрикс

Для вывода табличной инофрмации используется компонент : bitrix:main.ui.grid

Для фильтрации по таблице – компонент: bitrix:main.ui.filter

<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_admin_before.php");
 
use \Bitrix\Iblock\PropertyEnumerationTable;
use Bitrix\Main\Grid\Options as GridOptions;
use Bitrix\Main\UI\PageNavigation;
 
IncludeModuleLangFile(__FILE__);
 
 
 
Bitrix\Main\Loader::IncludeModule("coderun.optlk");
Bitrix\Main\Loader::IncludeModule("coderun.racingchampions");
 
$POST_RIGHT = $APPLICATION->GetGroupRight("coderun.optlk");
 
$APPLICATION->SetTitle(GetMessage("CODERUN_LK_LK_CLIENT_LIST_TITLE"));
 
$list_id = \Coderun\Racingchampions\ChampionsInfoTable::getTableName(); //Индификатор таблицы
 
$grid_options = new GridOptions($list_id);
 
//$sort = $grid_options->GetSorting(['sort' => ['ID' => 'DESC'], 'vars' => ['by' => 'by', 'order' => 'order']]);
 
/**
 * Навигация
 */
$nav_params = $grid_options->GetNavParams();
 
$nav = new PageNavigation('request_list');
 
$nav->allowAllRecords(true)//Показать все
        ->setRecordCount($DB->query("SELECT COUNT(*) as CNT FROM coderun_transport_champions_info")->fetch()['CNT'])//Для работы кнопки "показать все"
        ->setPageSize($nav_params['nPageSize'])//Параметр сколько отображать на странице
        ->initFromUri();
 
 
 
/**
 * Параметры запроса
 */
$sql_where = 'WHERE 1=1';
 
$sql_joint = '';
 
$sql_order = 'ORDER BY `ID` ASC';
 
$sql_limit = 'LIMIT ' . $nav->getLimit();
 
$sql_offset = 'OFFSET ' . $nav->getOffset();
 
/**
 * Сортировка
 */
if (($_GET['grid_id'] ?? null) === $list_id) {
    if (isset($_GET['grid_action']) and $_GET['grid_action'] === 'sort') {
        $sql_order = "ORDER BY `{$DB->ForSql($_GET['by'])}` {$DB->ForSql($_GET['order'])}";
    }
}
 
/**
 * Фильтрация
 */
$filterOption = new Bitrix\Main\UI\Filter\Options($list_id);
 
$filterData = $filterOption->getFilter([]);
 
$filter = [];
 
foreach ($filterData as $key => $value) {
 
    /**
     * Фильтр по датам
     */
    if (stripos($key, 'DATE_GIFT') !== FALSE) {
 
        //DATE_GIFT_datesel == RANGE,TOMORROW,
        $date_start = strtotime($filterData['DATE_GIFT_from']);
 
        $date_end = strtotime($filterData['DATE_GIFT_to']);
 
        $sql_where .= " AND checkpoint_user.DATE_CREATE BETWEEN FROM_UNIXTIME({$date_start}) AND FROM_UNIXTIME({$date_end})";
    }
 
    /**
     * Фильтр контрагент
     */
    if ($key === 'CODE_PARTNER' && strlen($value) > 0) {
        $sql_where .= " AND champions_info.CODE_PARTNER='{$value}'";
    }
 
    /**
     * фильтр дистанция
     */
    if ($key === 'DISTANCE' && strlen($value) > 0) {
        $sql_where .= " AND DISTANCE>={$value}";
    }
 
    /**
     * фильтр телефон менеджера
     */
    if ($key === 'PHONE' && strlen($value) > 0) {
        $sql_where .= " AND MANAGER.PHONE='{$value}'";
 
        $sql_joint .= <<<EOT
            LEFT JOIN `coderun_lk_parners_managers_partners` AS manager_partner ON manager_partner.PARTNER_ID=parners.ID
            LEFT JOIN `coderun_lk_parners_managers` as `MANAGER` ON `MANAGER`.`ID` = `manager_partner`.`MANAGER_ID`         
EOT;
    }
 
    /**
     * Фильтр название контрагента
     */
    if ($key === 'NAME' && strlen($value) > 0) {//фильтр имя
        $sql_where .= " AND NAME LIKE '%{$DB->ForSql($value)}%'";
    }
 
    /**
     * Фильтр кто хотя бы 1-н раз активировал литры
     */
    if ($key === 'FIRST_LITER' && strlen($value) > 0) {
        $sql_joint .= <<<EOT
            LEFT JOIN `coderun_transport_champions_fuel` AS fuel_list ON fuel_list.CODE_PARTNER=parners.GROUP_ID
EOT;
        $sql_where .= " AND fuel_list.VALUE>0 AND fuel_list.STATUS='Y'";
    }
}
 
/**
 * Весь запрос
 */
$sql_query = <<<EOT
            SELECT 
           `champions_info`.`ID` AS `ID`, 
           `parners`.`NAME` AS `NAME`, 
           `champions_info`.`DISTANCE` AS `DISTANCE`, 
           `champions_info`.`CODE_PARTNER` AS `CODE_PARTNER`, 
           `champions_info`.`FUEL_ACTIVE` AS `FUEL_ACTIVE`, 
           `champions_info`.`CHARGE_OF_FUEL` AS `CHARGE_OF_FUEL`, 
           (
           SELECT
           IF(`VALUE`>0,SUM(`VALUE`),0)
           FROM
           coderun_transport_champions_fuel
           WHERE CODE_PARTNER=parners.GROUP_ID AND STATUS='N'
           ) AS FUEL_NO_ACTIVE,
           COUNT(`checkpoint_user`.`ID`) AS `CHECKPOINT_LIST_CNT` 
           FROM `coderun_transport_champions_info` as `champions_info` 
           LEFT JOIN `coderun_lk_parners` as `parners` ON `champions_info`.`CODE_PARTNER` = `parners`.`GROUP_ID` 
           LEFT JOIN `coderun_transport_champions_checkpoint_user` as `checkpoint_user` ON `champions_info`.`CODE_PARTNER` = `checkpoint_user`.`CODE_PARTNER` 
           {$sql_joint}
           {$sql_where}
           GROUP BY 
           `parners`.`GROUP_ID`
           {$sql_order}
           {$sql_limit}
           {$sql_offset}
EOT;
 
/**
 * Результат запроса для отображения таблицы
 */
$rsData = $DB->query($sql_query);
 
/**
 * Список фильтров
 */
$filter_list = [
    [
        "id" => "ID",
        'type' => 'number',
        "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_CLIENT_ID"),
        "default" => true,
    ],
    [
        "id" => "NAME",
        'type' => 'text',
        "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_NAME"),
        "default" => true
    ],
    [
        "id" => "PHONE",
        'type' => 'text',
        "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_PHONE"),
        "default" => true
    ],
    [
        "id" => "CODE_PARTNER",
        'type' => 'text',
        "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_XML_ID"),
        "default" => true
    ],
    [
        "id" => "DATE_GIFT",
        'type' => 'date',
        "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_DATE_GIFT"),
        "default" => true
    ],
    [
        "id" => "FIRST_LITER",
        'type' => 'list',
        'items' => ['Y' => 'Показать'],
        //'params' => ['multiple' => 'Y'],
        "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_FIRST_LITER"),
        "default" => true
    ],
];
 
/**
 * Колонки таблицы
 */
$arHeaders = array(
    array("id" => "ID", "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_CLIENT_ID"), "sort" => "ID", "align" => "center", "default" => true),
    array("id" => "NAME", "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_NAME"), "sort" => "NAME", "align" => "center", "default" => true),
    //array("id" => "CODE_PARTNER", "content" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_XML_ID"), "sort" => "", "align" => "left", "default" => true),
    array("id" => "DISTANCE", "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_DISTANCE"), "sort" => "DISTANCE", "align" => "center", "default" => true),
    array("id" => "FUEL_ACTIVE", "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_FUEL_ACTIVE"), "sort" => "FUEL_ACTIVE", "align" => "center", "default" => true),
    array("id" => "FUEL_NO_ACTIVE", "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_FUEL_NO_ACTIVE"), "sort" => "FUEL_NO_ACTIVE", "align" => "center", "default" => true),
    array("id" => "CHARGE_OF_FUEL", "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_CHARGE_OF_FUEL"), "sort" => "CHARGE_OF_FUEL", "align" => "center", "default" => true),
    array("id" => "CHECKPOINT_LIST_CNT", "name" => GetMessage("CODERUN_LK_LK_CLIENT_LIST_TABLE_CHECKPOINT"), "sort" => "CHECKPOINT_LIST_CNT", "align" => "center", "default" => true),
);
 
require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_admin_after.php");
?>
<div class="adm-toolbar-panel-container">
    <div class="adm-toolbar-panel-flexible-space">
        <?php
        $APPLICATION->IncludeComponent('bitrix:main.ui.filter', '', [
            'FILTER_ID' => $list_id,
            'GRID_ID' => $list_id,
            'FILTER' => $filter_list,
            'ENABLE_LIVE_SEARCH' => true,
            'ENABLE_LABEL' => true
        ]);
        ?>
    </div>
    <div class="adm-toolbar-panel-align-right">
    </div>
</div>
 
<?php
/**
 * Данные по каждому выбранному элементу таблицы
 */
$list = [];
while ($row = $rsData->fetch()) {
 
    $url_params = http_build_query(
            [
                'CODE_PARTNER' => $row['CODE_PARTNER'],
                'lang' => LANGUAGE_ID,
                'ID' => $row['ID'],
            ]
    );
 
    $list[] = [
        'data' => $row,
        'actions' => [
            [
                'text' => 'Просмотр',
                'default' => true,
                'onclick' => "document.location.href='/bitrix/admin/coderun_lk_partners_action_racing_card.php?{$url_params}'"
            ],
//            [
//                'text' => 'Удалить',
//                'default' => true,
//                'onclick' => 'if(confirm("Точно?")){document.location.href="?op=delete&id=' . $row['ID'] . '"}'
//            ]
        ]
    ];
}
 
//\Bitrix\Main\Page\Asset::getInstance()->addCss('/bitrix/css/main/grid/webform-button.css');
 
$APPLICATION->IncludeComponent('bitrix:main.ui.grid', '', [
    'GRID_ID' => $list_id,
    'COLUMNS' => $arHeaders,
    'ROWS' => $list,
    'SHOW_ROW_CHECKBOXES' => false,
    'NAV_OBJECT' => $nav,
    'AJAX_MODE' => 'Y',
    'AJAX_ID' => \CAjax::getComponentID('bitrix:main.ui.grid', '.default', ''),
    'PAGE_SIZES' => [
        ['NAME' => '5', 'VALUE' => '5'],
        ['NAME' => '20', 'VALUE' => '20'],
        ['NAME' => '50', 'VALUE' => '50'],
        ['NAME' => '100', 'VALUE' => '100']
    ],
    'AJAX_OPTION_JUMP' => 'N',
    'SHOW_CHECK_ALL_CHECKBOXES' => false,
    'SHOW_ROW_ACTIONS_MENU' => true,
    'SHOW_GRID_SETTINGS_MENU' => true,
    'SHOW_NAVIGATION_PANEL' => true,
    'SHOW_PAGINATION' => true,
    'SHOW_SELECTED_COUNTER' => true,
    'SHOW_TOTAL_COUNTER' => true,
    'SHOW_PAGESIZE' => true,
    'SHOW_ACTION_PANEL' => true,
    'ALLOW_COLUMNS_SORT' => true,
    'ALLOW_COLUMNS_RESIZE' => true,
    'ALLOW_HORIZONTAL_SCROLL' => true,
    'ALLOW_SORT' => true,
    'ALLOW_PIN_HEADER' => true,
    'AJAX_OPTION_HISTORY' => 'N',
    'TOTAL_ROWS_COUNT_HTML' => '<span class="main-grid-panel-content-title">Всего:</span> <span class="main-grid-panel-content-text">' . $nav->getRecordCount() . '</span>',
//    'ACTION_PANEL' => [
//        'GROUPS' => [
//            'TYPE' => [
//                'ITEMS' => [
//                    [
//                        'ID' => 'set-type',
//                        'TYPE' => 'DROPDOWN',
//                        'ITEMS' => [
//                            ['VALUE' => '', 'NAME' => '- Выбрать -'],
//                            ['VALUE' => 'plus', 'NAME' => 'Битые данные'],
//                        ]
//                    ],
//                    [
//                        'ID' => 'edit',
//                        'TYPE' => 'BUTTON',
//                        'TEXT' => 'Редактировать',
//                        'CLASS' => 'icon edit',
//                        'ONCHANGE' => ''
//                    ],
//                    [
//                        'ID' => 'delete',
//                        'TYPE' => 'BUTTON',
//                        'TEXT' => 'Удалить',
//                        'CLASS' => 'icon remove',
//                        'ONCHANGE' => $onchange->toArray()
//                    ],
//                ],
//            ]
//        ],
//    ],
]);

Источник: https://coderun.ru/blog/bitrix-grid-v-adminke-ili-kak-pokazyvat-tablichnye-dannye-v-svojom-module-krasivo/