Примеры UMI Selector — протокол выборки данных
Выдержка из wiki.umisoft.ru
Selector — механизм формирования выборок, который должен заменить использование umiSelection+umiSelectionParser. Замена механизма выборок вызвана желанием максимально упростить выборки, избавиться от необходимости использования дополнительных классов и упростить определение искомых полей.
Кроме этого UMI Selector работает намного быстрее чем umiSelection. Проверено на практике на 1 раз.
Эта статья будет иметь формат помощи, чтобы не нужно было переписывать один и тот же код по 300 раз, здесь будет пример готовых выборок. Для подробного знакомства с протоколом Selector обратитесь к официальной документации
Хочу вам напомнить, что для того, чтобы эти функции работали, вам нужно добавлять разрешения в permission.php или custom.permission.php
ВНИМАНИЕ!
- Данная статья не рассчитана на новичков.
- Все макросы работают только с XSLT-шаблонизатором. С TPL я не работаю и не пишу под него ничего.
Функция для выбора всех объектов каталога
public function getAllObjects() { $hierarchy = umiHierarchy::getInstance(); $sel = new selector('pages'); $sel->types('hierarchy-type')->name('catalog', 'object'); // Отрисовать элементы $lines = Array(); foreach ($sel->result as $item){ $element = $hierarchy->getElement($item->id); $arr['attribute:id'] = $item->id; $arr['attribute:link'] = $item->link; $arr['name'] = $element->name; $lines['nodes:item'][] = $arr; } return array( "items" => $lines, ); }
Функция для выбора всех объектов из определенного каталога товаров
Параметры:
$parent_id — id категории или путь
$limit — кол-во товаров выводимых на страницу
public function getProductsListFromCategory($parent_id = false, $limit = false) { $hierarchy = umiHierarchy::getInstance(); $sel = new selector('pages'); $sel->types('hierarchy-type')->name('catalog', 'object'); if(!$parent_id) { $category_url = explode('?', $_SERVER['REQUEST_URI']); $parent_id = $hierarchy->getIdByPath($category_url[0]); } if(!is_numeric($parent_id)) { $parent_id = $hierarchy->getIdByPath($parent_id); } if($parent_id && is_numeric($parent_id)) $sel->where('hierarchy')->page($parent_id)->childs(5); else return array( 'error' => 'Укажите id категории или передайте путь к категории' ); // Расскоментировть и указать поля для сортировки товаров по умолчанию // $sel->order('is_in_store')->desc(); // Переменная для проверки активированы ли фильтры if(getRequest('fields_filter')) // Активировать фильтрацию selectorHelper::detectFilters($sel); // Активировать сортировку товаров if(getRequest('order_filter')) selectorHelper::detectOrderFilters($sel); // Подключить постраничную навигацию $per_page = ($limit) ? $limit : $this->per_page; $curr_page = getRequest('p'); if(!$curr_page or $curr_page == 0) $offset = 0; else $offset = ($per_page * $curr_page); $sel->limit($offset, $per_page); // Отрисовать элементы $lines = Array(); foreach ($sel->result as $item){ $element = $hierarchy->getElement($item->id); $arr['attribute:id'] = $item->id; $arr['attribute:link'] = $item->link; $arr['name'] = $element->name; $lines['nodes:item'][] = $arr; } $lines['total'] = $sel->length; $lines['category_id'] = $parent_id; $lines['nodes:category_h1'] = $hierarchy->getElement($parent_id)->getValue('h1'); $lines['per_page'] = $per_page; $lines['nodes:numpages'] = umiPagenum::generateNumPage($sel->length, $per_page); return def_module::parseTemplate('', $lines); }
Если в данной функции у вас появятся ошибки, пожалуйста, сообщите мне. К сожалению, пишу на лету 🙂
Функция для вывода дерева каталога товаров. Вызывается рекурсивно. Работает быстрее чем стандартная функция getCategoryList!!! Состоит из двух частей:
getCatalogList () — получает список категорий из id указанного в $cat_id.
is_active () — проверяет активность раздела
public function getCatalogList($cat_id) { $hierarchy = umiHierarchy::getInstance(); $sel = new selector('pages'); $sel->types('hierarchy-type')->name('catalog', 'category'); if(!$cat_id) { $category_url = explode('?', $_SERVER['REQUEST_URI']); $cat_id = $hierarchy->getIdByPath($category_url[0]); } if(!is_numeric($cat_id)) { $cat_id = $hierarchy->getIdByPath($cat_id); } if($cat_id && is_numeric($cat_id)) $sel->where('hierarchy')->page($cat_id)->childs(1); else return array( 'error' => 'Укажите id категории или передайте путь к категории' ); $sel->limit(0, 100); // Отрисовать элементы $lines = Array(); foreach ($sel->result as $item){ $element = $hierarchy->getElement($item->id); $childs = $hierarchy->getChilds($item->id, true, true, 3); $arr['attribute:id'] = $item->id; $arr['attribute:link'] = $item->link; $arr['name'] = $element->name; if(count($childs) > 0) { $arr['attribute:childs'] = count($childs); } else { $arr['attribute:childs'] = 0; } $arr['attribute:class'] = $this->is_active($item->id); $lines['nodes:item'][] = $arr; } return array( "items" => $lines, ); } public function is_active($page_id, $mode = 'xslt'){ $currentPageId = cmsController::getInstance()->getCurrentElementId(); if($currentPageId) { static $allParentsIds = null; if(is_null($allParentsIds)) { $allParentsIds = umiHierarchy::getInstance()->getAllParents($currentPageId, true); } $page_id = (int) $page_id; $result = in_array($page_id, $allParentsIds) ? true : false; } else { $result = false; } switch ($mode){ case 'tpl': if($result) return 'active'; break; case 'xslt': if($result) return 'active'; //1; else return ''; break; } }
Шаблон XSLT
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE xsl:stylesheet SYSTEM "ulang://i18n/constants.dtd:file"> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:umi="http://www.umi-cms.ru/TR/umi"> <xsl:template name="catalogList"> <div class="b-left-column__title"> <xsl:text>&catalog;</xsl:text> </div> <div class="b-left-column__catalog"> <ul> <xsl:apply-templates select="document('udata://catalog/getCatalogList/(shop)')/udata/items/item" mode="catalogList" /> </ul> </div> </xsl:template> <xsl:template match="item" mode="catalogList"> <li class="{@class}"> <a href="{@link}" title="{name}"> <xsl:value-of select="name" /> </a> <xsl:if test="@childs > 0"> <ul> <xsl:apply-templates select="document(concat('udata://catalog/getCatalogList/', @id))/udata/items/item" mode="catalogList" /> </ul> </xsl:if> </li> </xsl:template> </xsl:stylesheet>
Продолжение следует