mixed CIBlockElement::GetIBlockByID(
int ID
);
Метод возвращает инфоблок по ID его элемента. Метод статический.
Параметры вызова
Параметр | Описание |
---|---|
ID | ID элемента. |
Возвращаемое значение
Метод возвращает идентификатор инфоблока по ID его элемента или false, если элемент не найден.
Пользовательские комментарии
Мы будем рады, если разработчики добавят свои комментарии по практическому использованию методов системы.
Для этого нужно всего лишь авторизоваться на сайте
Но помните, что Пользовательские комментарии, несмотря на модерацию, не являются официальной документацией. Ответственность за их использование несет сам пользователь.
Также Пользовательские комментарии не являются местом для обсуждения функционала. По подобным вопросам обращайтесь на форумы.
а в админке скорее всего не как, создайте страничку с кодом
if(!CModule::IncludeModule("iblock")) return;
<?
$res = CIBlockElement::GetByID(%сюда ваш ID%);
if($ar_res = $res->GetNext())
var_dump($ar_res);
?>
не забудьте подключить хедер футер или пролог
<ваш сайт>/bitrix/admin/sql.php
select ID, IBLOCK_ID, IBLOCK_SECTION_ID from b_iblock_element where ID = <ваш id>
Для поиска в bitrix элемента ифноблока по id надо воспользоваться следующим кодом. На вход подаётся Id, а так же подключаются инфоблоки IncludeModule(‘iblock’)
CModule::IncludeModule(‘iblock’); $ID=12; $res = CIBlockElement::GetList(array(), array(‘ID’=>$ID), false, false, array(‘ID’, ‘IBLOCK_ID’, ‘NAME’, ‘DETAIL_PAGE_URL’)); if ($arElement = $res->GetNext()) { // echo «<pre>»; print_r($arElement); echo «</pre>»; } |
Поиск в битриксе названия раздела по id, так же прост. Тут же мы может вытащить все остальные данные раздела. Смотрим код ниже.
$ATT_REG=32; $res = CIBlockSection::GetByID($ATT_REG); if($ar_res = $res->GetNext()){ $name_reg= $ar_res[‘NAME’]; print_r($ar_res); } |
Стандартно 1С-Битрикс не ищет по ID. Исправляем этот момент 🙂
Для поиска контента на сайте, обычно используют bitrix:search.title или компонент Поиск по заголовкам. Данный компонент (как несложно догадаться) ищет по названиям элементов, и выдает вам результат аяксом сразу же под поисковой строкой. В настройках вы можете ограничить область поиска выбрав нужные инфоблоки.
На моей практике, самый популярный случай это поиск по Каталогу, а точнее – по названию товара. Перейдем к реализации.
Шаг 1. Свойство в админке + init.php
Создадим в админке свойство с символьным кодом MYID и в настройках ставим галочку Значения свойства участвуют в поиске.
Теперь, переиндексируем все элементы. Для этого создаем страницу со следующим содержимым:
<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");?> <? set_time_limit(0); if (CModule::IncludeModule("iblock")): $res = CIBlockElement::GetList ( false, Array("IBLOCK_ID" => 38, "ACTIVE" => "Y"), false, false, Array('ID', 'NAME', 'PROPERTY_MYID') ); while($ar_field = $res->GetNext()) { #Запись в MYID текущего ID if(!$ar_field['PROPERTY_MYID_VALUE']) { CIBlockElement::SetPropertyValuesEx($ar_field['ID'], false, array("MYID" => $ar_field['ID'])); echo "<pre>Товар перезаписан - ".$ar_field['NAME']." - в значении ".$ar_field['ID']."</pre>"; } } echo 'Работа скрипта завершена'; endif; ?> <?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");?>
38 – ID вашего инфоблока с товарами. Мы записываем в свойство наш ID, если оно не задано. По этому свойству мы и будем искать. После того как скрипт выполнится, его можно удалить.
ПС – как вы видите, я в настройках фильтрации не указывал:
Array("IBLOCK_ID" => 38, "ACTIVE" => "Y", "!PROPERTY_MYID_VALUE" => false),
Хотя наверное стоило 🙂 .
Чтобы не вбивать в ручную ID, добавим в init.php следующий код:
/* добавляем в поисковый индекс ID нового товара */ AddEventHandler("iblock", "OnAfterIBlockElementAdd", "searchid"); function searchid(&$arFields){ if($arFields["ID"]>0){ $upd = CIBlockElement::SetPropertyValuesEx( $arFields["ID"], $arFields['IBLOCK_ID'], array('MYID' => $arFields["ID"]) ); } }
Это позволит при создании нового товара сразу же записывать его ID.
init.php это файл который создается в папке /bitrix/php_interface/
Шаг 2. Переиндексация
Теперь нам необходимо запустить переиндексацию. Делается это весьма просто:
http://ВАШ_САЙТ/bitrix/admin/search_reindex.php?lang=ru
ВАШ_САЙТ – вставляем домен и вуаля, вы на странице. Убираем галочку Переиндексировать только измененные и запускаем.
Шаг 3. Перенос компонента
На это шаге вам необходимо скачать компонент. Помещаем его в папку /bitrix/components/. Обратите внимание, что пространство имен компонента не bitrix а ready. К сожалению обычный компонент на рассчитан на поиск по другим свойствам, только по заголовкам.
<?$APPLICATION->IncludeComponent( "ready:search.title", .. ?>
Надеюсь вы знаете, как в этот код добавить параметры и вызвать компонент 🙂 Для простоты, можно просто поменять в вашем search.title birix на ready. Зачем мы это делаем не в папке битрикс? Потому что при обновлении эти файлы могут обновиться, и в какой-то момент вы зададите себе вопрос “почему ничего не работает?” 🙂 .
Для самых любопытных оставляю ссылку на документацию.
Если на вашем сайте необходимо выполнить Поиск по id товара или элемента обращайтесь ко мне, помогу с настройкой
Returns list of elements filtered by arFilter. Static method.
Important! Starting from Information blocks module version 18.6.200 the method has new options to handle products, with updated method keys. Correspondingly, all CATALOG_***
parameters have deprecated.
Attention: Starting from Information blocks module version 20.5.0, the method no longer processes the keys CHECK_BP_TASKS_PERMISSIONS and TASKSTATUS.
Note: Fields listed for sorting will be automatically added to the parameter arSelectFields or arGroupBy with specified grouping.
See Also
Parameters
Parameter | Description | Available from version |
---|---|---|
arOrder | Array type: Array(by1=>order1[, by2=>order2 [, ..]]), where by — field for sorting. It can have the following values:
Note 1: when you indicate the same symbolic code to different properties, but with different case, it results in an error when sorting by a property (for example, PROPERTY_rating) — listed elements will be duplicated, sorting won’t happen. Note 2: indicated sorting fields are added to arGroupBy (if specified) and arSelectFields. |
|
arFilter | An array of the format Array(«filter field»=>»filter value» [, …]) where the «filtering field» can be the following:
The following modifiers are possible before the field name:
The «filter values» are a single value or an array. This parameter is optional. No filtering is performed by default. Note 1: (for filter setup for «Date/Time» property type): Date/Time property type is stored as string with date with format YYYY-MM-DD HH:MI:SS. Accordingly, sorting by the value of such property will operate correctly, but the value for filtering is generated approximately as follows: $cat_filter[«>».»PROPERTY_available»] = date(«Y-m-d»); Note 2: when using «><» filter verification type for integers, ending at zero, you need to use the number field type or separator character «,» for decimal values (for example, 20000,00). Otherwise, operates incorrectly. |
|
arGroupBy | If this parameter is not false, the returned items are grouped accordingly and the result array includes a CNT key returning the number of grouped elements; the arSelectFields is ignored. If the arGroupBy is an empty array, the method returns the number of elements in the CNT key. The grouping can be performed by the property values instead of the element fields. To do so, specify PROPERTY_<PROPERTY_CODE> Optional. The returned items are not grouped by default (false). |
|
arNavStartParams | These parameters are used to implement breadcrumbs. This is achieved by passing an array of pairs «parameter=>value» with the following parameters:
This parameter is optional.
The default value is false which specifies to return a full selection. |
|
arSelectFields | Array with returned element fields.
Attention! The parameter uses fields, but not arrays. This way, an attempt to fetch by IBLOCK_SECTION (Array with group identifiers, including this element) results in disrupted method performance. List of element fields can show the values of its properties. You must use the fields IBLOCK_ID and ID, otherwise it will operate incorrectly. Additionally, you need to indicate PROPERTY_<PROPERTY_CODE>, as one of fields, where PROPERTY_CODE — ID or symbolic code (specified in upper case, even if it’s specified in lower case in the defined iblock property). The result will print element properties as fields PROPERTY_<PROPERTY_CODE>_VALUE — value; PROPERTY_<PROPERTY_CODE>_ID — element code; PROPERTY_<PROPERTY_CODE>_ENUM_ID — value code (for list properties). You can show element prices as well with the installed Commercial catalog module. You must indicate *CATALOG_GROUP_<PRICE_CODE>, where PRICE_CODE — price type ID. Also, you can retrieve element fields by «Bind to elements» property values. You must indicate PROPERTY_<PROPERTY_CODE>.<FIELD>, where PROPERTY_CODE — ID or binding property symbolic code, and FIELD — is the field of element specified in the binding. See «Bind element fields for sorting». You can also fetch element property values by «Bind to element» property values. You must indicate PROPERTY_<PROPERTY_CODE>.PROPERTY_<PROPERTY_CODE2>, where PROPERTY_CODE — ID or binding property code, and PROPERTY_CODE2 — element property specified in the binding. By default, all the element fields are retrieved. Parameter values are ignored when using the grouping parameter arGroupBy. Note 1: If a multiple property is specified in this parameter, the method will return multiple records for elements that contain more than one values of such property. To fix this problem, the information blocks may be set to store properties in individual tables. In this case, the method will return multiple values as an array. Another approach is to retrieve the properties by calling _CIBElement::GetProperties() on each iteration instead of using the arSelectFields. Note 2: If this parameter specifies DETAIL_PAGE_URL, SECTION_PAGE_URL or LIST_PAGE_URL, the fields required to resolve the URL templates will be determined automatically unless grouping is in effect. Note 3: To retrieve rating data for the selected elements, use the following keys in this parameter: RATING_TOTAL_VALUE, RATING_TOTAL_VOTES, RATING_TOTAL_POSITIVE_VOTES, RATING_TOTAL_NEGATIVE_VOTES, RATING_USER_VOTE_VALUE. |
|
* — Parameters type CATALOG_*** have deprecated since Iblocks module version 18.6.200. |
||
** — In case the parameters arGroupBy passes an empty array — the parameter arNavStartParams data is ignored. | ||
Useful filters
- $arFilter = array(«PROPERTY_CML2_SCAN_CODE») =>»» : returns all elements;
- $arFilter = array(«PROPERTY_CML2_SCAN_CODE») =>false : returns all elements with empty values;
- $arFilter = array(«PROPERTY_CML2_SCAN_CODE») =>»abc» : returns all elements whose scan code maches «abc» exactly;
- $arFilter = array(«?PROPERTY_CML2_SCAN_CODE») =>»def» : returns all elements whose scan code contains the substring «def».
- $arFilter = array(«!PROPERTY_CML2_SCAN_CODE») =>»» : returns all elements whose CML2_SCAN_CODE property is not empty;
- $arFilter = array(«!PROPERTY_CML2_SCAN_CODE») =>false : returns only the elements with non-empty property values;
- $arFilter = array(«!PROPERTY_CML2_SCAN_CODE») =>»abc» : returns all elements whose CML2_SCAN_CODE property value is not «abc»;
- $arFilter = array(«!?PROPERTY_CML2_SCAN_CODE») =>»def» : returns all elements whose CML2_SCAN_CODE property value does not include a «def» substring.
Using complex logic in filters
The arFilter parameter may specify nested filters in the form of an array. The nested filter array contains entries whose
key is an ordinal number, and the values are the filter conditions (which can be anything including arrays).
Theoretically, there is no restriction on the level of filter nesting.
The filter condition may be set to use conjunction or disjunctions logic. That is, «AND» or «OR».
«AND» specifies that all of the filter conditions must be true to pass; «OR» – one of the filter conditions must be true.
To specify the logic operator, use the LOGIC key.
Example
The following code selects little ripe oranges and big unripe ones:
$arFilter = array(
"IBLOCK_ID" => $IBLOCK_ID,
"SECTION_CODE" => "orange",
"INCLUDE_SUBSECTIONS" => "Y",
array(
"LOGIC" => "OR",
array("<PROPERTY_RADIUS" => 50, "=PROPERTY_CONDITION" => "Y"),
array(">=PROPERTY_RADIUS" => 50, "!=PROPERTY_CONDITION" => "Y"),
),
);
Fields of bound elements
- ID — the element ID;
- TIMESTAMP_X – the date and time an element was last modified, in the current website format;
- MODIFIED_BY – the ID of a user who was the last to modify an element;
- DATE_CREATE – the date and time an element was created;
- CREATED_BY — the ID of a user who created an element;
- IBLOCK_ID — the information block ID;
- ACTIVE — the element active status (Y|N);
- ACTIVE_FROM — the date and time since when an element is active, in the current website format;
- ACTIVE_TO — the latest date and time when an element is active, in the current website format;
- SORT — the sort order;
- NAME — the element name;
- PREVIEW_PICTURE — the thumbnail image ID;
- PREVIEW_TEXT — the short text;
- PREVIEW_TEXT_TYPE — type of the short text (html|text);
- DETAIL_PICTURE — the large image ID;
- DETAIL_TEXT – the detailed text;
- DETAIL_TEXT_TYPE — type of the detailed text (html|text);
- SHOW_COUNTER – the value of the impression counter;
- SHOW_COUNTER_START – the date and time of the very first impression, in the website format;
- CODE – the element symbolic code;
- TAGS – the element tags;
- XML_ID – the external ID;
- IBLOCK_SECTION_ID – the ID of the element’s parent section (if present).
The following fields describe an information block.
- IBLOCK_TYPE_ID – the information block type ID;
- IBLOCK_CODE – the information block symbolic code;
- IBLOCK_NAME – the information block name;
- IBLOCK_EXTERNAL_ID – the information block external ID;
- DETAIL_PAGE_URL – the element page URL template as specified in the information block parameters;
- LIST_PAGE_URL – the elements list page URL template as specified in the information block parameters.
Examples
Example 1:
<? $arSelect = Array("ID", "NAME", "DATE_ACTIVE_FROM"); $arFilter = Array("IBLOCK_ID"=>IntVal($yvalue), "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y"); $res = CIBlockElement::GetList(Array(), $arFilter, false, Array("nPageSize"=>50), $arSelect); while($ob = $res->GetNextElement()) { $arFields = $ob->GetFields(); print_r($arFields); } ?>
Example can be updated by adding property display for each item. It’s convenient for use, without the need to implement GetProperty. In case of Iblocks 2.0, you need to add IBLOCK_ID to $arSelect.
<? $arSelect = Array("ID", "IBLOCK_ID", "NAME", "DATE_ACTIVE_FROM","PROPERTY_*");//IBLOCK_ID and ID must be specified, see description of arSelectFields above $arFilter = Array("IBLOCK_ID"=>IntVal($yvalue), "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y"); $res = CIBlockElement::GetList(Array(), $arFilter, false, Array("nPageSize"=>50), $arSelect); while($ob = $res->GetNextElement()){ $arFields = $ob->GetFields(); print_r($arFields); $arProps = $ob->GetProperties(); print_r($arProps); } ?>
Example 2:
<? // selection of active items from $yvalue iblock, // with property value set with SRC character code // and activity start date older than 1 January 2003 // selected items can be grouped by activity date $arFilter = Array( "IBLOCK_ID"=>IntVal($yvalue), ">DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT")), mktime(0,0,0,1,1,2003)), "ACTIVE"=>"Y", "!PROPERTY_SRC"=>false ); $res = CIBlockElement::GetList(Array("SORT"=>"ASC", "PROPERTY_PRIORITY"=>"ASC"), $arFilter, Array("DATE_ACTIVE_FROM")); while($ar_fields = $res->GetNext()) { echo $ar_fields["DATE_ACTIVE_FROM"].": ".$ar_fields["CNT"]."<br>"; } ?>
Example 3:
//displaying archive from expired items (news.list) $arFilter = array( "IBLOCK_ID" => $arResult["ID"], "IBLOCK_LID" => SITE_ID, "ACTIVE" => "Y", "CHECK_PERMISSIONS" => "Y", //singificantly overloads the system, but verifies access permissions " DateFormatToPHP(CLang::GetDateFormat("SHORT")), );
Example 4:
//selection of iblock items, to have 5 random items in the returned result $rs = CIBlockElement::GetList ( Array("RAND" => "ASC"), Array("IBLOCK_ID" => $IBLOCK_ID), false, Array ("nTopCount" => 5) );
Example 5:
//use subqueries for filtering by several values of multiple property CModule::IncludeModule('iblock'); $rs = CIBlockElement::GetList( array(), array( "IBLOCK_ID" => 21, array("ID" => CIBlockElement::SubQuery("ID", array("IBLOCK_ID" => 21, "PROPERTY_PKE" => 7405))), array("ID" => CIBlockElement::SubQuery("ID", array("IBLOCK_ID" => 21, "PROPERTY_PKE" => 7410))), array("ID" => CIBlockElement::SubQuery("ID", array("IBLOCK_ID" => 21, "PROPERTY_PKE" => 7417))) ), false, false, array("ID") ); while($ar = $rs->GetNext()) { echo '<pre>'; print_r($ar); echo '</pre>'; }
Example 6:
//next and previous product with account of sorting and in detail view $arrSortAlown = array('price'=> 'catalog_PRICE_1' , 'name'=> 'NAME', 'rating' => 'PROPERTY_RATING' , 'artnumber'=> 'PROPERTY_ARTNUMBER'); $_sort = isset($arrSortAlown[$_GET['sort']]) ? $arrSortAlown[$_GET['sort']] : 'NAME'; $_order = isset($_GET['order']) && $_GET['order']=='desc' ? 'DESC' : 'ASC'; $sort_url = 'sort=' .( isset($_GET['sort'])? $_GET['sort'] : 'name') .'&order='. (isset($_GET['order'])? $_GET['order'] : 'asc'); $res = CIBlockElement::GetList( array("$_sort" => $_order), Array( "IBLOCK_ID"=>$arResult["IBLOCK_ID"], "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y" , "IBLOCK_SECTION_ID" => $arResult["IBLOCK_SECTION_ID"] ), false, array("nPageSize" => "1","nElementID" => $arResult["ID"]), array_merge(Array("ID", "NAME","DETAIL_PAGE_URL"), array_values($arrSortAlown)) ); $navElement = array(); while($ob = $res->GetNext()){ $navElement[] = $ob; } //printed: <noindex> <div class="navElement" style="float:right; clear:both;"> <span class="l"> <small><a href="<?=$navElement[0]['DETAIL_PAGE_URL']?>?<?=$sort_url?>">Previous product</a></small> </span> <span class="r"> <small><a href="<?=$navElement[2]['DETAIL_PAGE_URL']?>?<?=$sort_url?>">Next product</a></small> </span> </div> </noindex>
Example 7:
//prints undue and thus inactive event notices without component updates // indicate filter name in the component and add filter itself in front of component: <? $arrFilter=Array(array( "LOGIC" => "OR", array("DATE_ACTIVE_TO"=>false), array(">DATE_ACTIVE_TO"=>ConvertTimeStamp(time(),"FULL")) )); ?>
Example 8:
//Iblock v18.6.700 now has option to sort the selected ID order, specified in the array // sort IDs as follows $ids = [115, 120, 117, 109, 128]; $rs = CIBlockElement::GetList( ['ID' => $ids], ['IBLOCK_ID' => '5', 'ID' => $ids], false, false, ['ID', 'IBLOCK_ID', 'NAME'] ); while ($ar = $rs->Fetch()) { echo $ar['ID'] . ' '; } // printed result: // 115 120 117 109 128
Example 9:
//Iblock v21.700.100 now has an added nOffset key in arNavStartParams BitrixMainLoader::includeModule('iblock'); $res = CIBlockElement::GetList( ['ID' => 'ASC'], ['IBLOCK_ID' => 2], false, ['nTopCount' => 5, 'nOffset' => 1000], ['ID', 'IBLOCK_ID', 'NAME'] ); while ($row = $res->Fetch()) { echo '<pre>', mydump($row), '</pre>'; } // nTopCount - amount // nOffset - indicated offset
Example 10. Print elements with non-empty value of list multiple property
${$FILTER_NAME}[]=array( "ID" => CIBlockElement::SubQuery("ID", array( "IBLOCK_ID" => $arParams['IBLOCK_ID'], "!=PROPERTY_".$arProp["CODE"] => false )) );
Example 11. Creating search by catalog using the field SEARCHEBLE_CONTENT.
<? CModule::IncludeModule('iblock'); $IBLOCK_ID = intval($_REQUEST['IBLOCK_ID']); $QUERY = trim($_REQUEST['q']); if($QUERY) { $arSelect = Array("ID", "NAME", "DATE_ACTIVE_FROM", "DETAIL_PAGE_URL", "PREVIEW_PICTURE"; $arFilter = Array("IBLOCK_ID"=>$IBLOCK_ID, "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y", "SEARCHABLE_CONTENT"=>'%'.$_REQUEST['q'].'%'); $res = CIBlockElement::GetList(Array(), $arFilter, false, Array("nPageSize"=>50), $arSelect); while($ob = $res->GetNextElement()) { $arFields = $ob->GetFields(); print_r($arFields); } } ?>
Example 12. For filtering by Date, i. e. from 12.09.2014 to 18.09.2014 inclusively, the filter will look as follows:
$date_from = '12.09.2014'; $date_to = '18.09.2014'; $db_el = CIBlockElement::GetList( array('ID' => 'DESC'), array( '>=DATE_CREATE' => $date_from, '<=DATE_CREATE' => $date_to . ' 23:59:59' ) );
© «Bitrix24», 2001-2023
Up