Здравствуйте, дорогие друзья и коллеги! Хочу познакомить вас с отличным пакетом для организации поиска на сайте под системой Modx Revolution - SimpleSearch . Я пошагово объясню вам, как установить этот пакет на сайт и организовать поиск на сайте. Итак, приступим:
1. Для начала заходим в "Система" - "Управление пакетами"
2. Жмем кнопку "Загрузить дополнения"
3. Вбиваем в строку поиска - SimpleSearch, нажимаем "Enter" и нажимаем на кнопку "Загрузить"
4. Пойдет загрузка пакета
5. Нажимаем "Управление пакетами"
6. И жмем кнопку "установить" возле скаченного нами SimpleSearch
Жмем "Продолжить", а потом "ОК"
7. Создаем новый ресурс в корне дерева
Заголовок: Результаты поиска, ставим галочку "Не показывать в меню". Нажимаем на вкладку "Настройки" и убираем галочки с "Доступен для поиска", "Использовать HTML-редактор". Незабываем сохранить ресурс.
8. Далее заходим в новосозданный ресурс и в поле "Содержимое ресурса" вписываем
[[!SimpleSearch]]9. Запоминаем id этого ресурса, это страница вывода результатов поиска
В шаблон где находится сама форма поиска вставляем следующий код:
[[!SimpleSearchForm? &landing=`1` &tpl=`search`]]
где landing - это ID страницы вывода результатов поиска, а чанк search отвечает за саму форму поиска, который мы сейчас создадим
10. Затем копируем следующий код
это содержимое файла core/components/simplesearch/elements/chunks/searchform.chunk.tpl:
в новый чанк с названием search и создаем тот шаблон отображения окна поиска, который нам необходим.
11. Далее решаем проблемы с кодировкой
Находим файл core/components/simplesearch/model/simplesearch/simplesearch.class.php в нем заменяем строку
$text = trim(preg_replace("/\s+/", " ", $this->sanitize($text)));
$text = trim(preg_replace("/\s+/u", " ", $this->sanitize($text)));
12. Затем заменяем строку
$string = preg_replace("/" . $quoteValue . "/i", "<".$tag." class=".$cls.">$0".$tag.">", $string);$string = preg_replace("/" . $quoteValue . "/iu", "<".$tag." class=".$cls.">$0".$tag.">", $string);
13. А так же заменяем строку
$text = preg_replace("/(\[\[\+.*?\]\])/i", "", $text);$text = preg_replace("/(\[\[\+.*?\]\])/iu", "", $text);
14. И последнее, надо закомментировать строчку
if (!empty($str)) $this->searchString = strip_tags($this->modx->sanitizeString($str));Основные чанки SimpleSearch
Поиск на сайте под управлением Modx Revolution готов. Он работает, можете убедиться в этом сами, но есть еще несколько моментов, которые пригодятся в работе с этим сниппетом. А именно редактирование чанков результатов поиска, его обертки, пагинации и так далее. Для начала Вам нужно понимать, что все чанки в формате.tpl находятся вот по этому пути: core/components/simplesearch/elements/chunks/. Ну а для того, чтобы с ними было легче работать выведем основные чанки в админку Modx. Вот их параметры
- containerTpl
- pageTpl
- currentPageTpl
Ну а называть сами чанки мы уже будем как хотим.
Параметр tpl - чанк SimpleSearchResult
Параметр tpl отвечает за вывод каждого отдельного пункта результата поиска. Давайте создадим чанк и назовем его SimpleSearchResult . Скопируем в него код из файла core/components/simplesearch/elements/chunks/searchresult.chunk.tpl :
[[+idx]].
2. Жмем кнопку "Загрузить дополнения"
3. Вбиваем в строку поиска - SimpleSearch, нажимаем "Enter" и нажимаем на кнопку "Загрузить"
4. Пойдет загрузка пакета
5. Нажимаем "Управление пакетами"
6. И жмем кнопку "установить" возле скаченного нами SimpleSearch
Жмем "Продолжить", а потом "ОК"
7. Создаем новый ресурс в корне дерева
Заголовок: Результаты поиска, ставим галочку "Не показывать в меню". Нажимаем на вкладку "Настройки" и убираем галочки с "Доступен для поиска", "Использовать HTML-редактор". Незабываем сохранить ресурс.
8. Далее заходим в новосозданный ресурс и в поле "Содержимое ресурса" вписываем
[[!SimpleSearch]]
9. Запоминаем id этого ресурса, это страница вывода результатов поиска
В шаблон где находится сама форма поиска вставляем следующий код:
[[!SimpleSearchForm? &landing=`1` &tpl=`search`]]
где landing - это ID страницы вывода результатов поиска, а чанк search отвечает за саму форму поиска, который мы сейчас создадим
10. Затем копируем следующий код
это содержимое файла core/components/simplesearch/elements/chunks/searchform.chunk.tpl:
в новый чанк с названием search
и создаем тот шаблон отображения окна поиска, который нам необходим.
11. Далее решаем проблемы с кодировкой
Находим файл core/components/simplesearch/model/simplesearch/simplesearch.class.php в нем заменяем строку
$text = trim(preg_replace("/\s+/", " ", $this->sanitize($text)));
$text = trim(preg_replace("/\s+/u", " ", $this->sanitize($text)));
12. Затем заменяем строку
$string = preg_replace("/" . $quoteValue . "/i", "<".$tag." class=".$cls.">$0".$tag.">", $string);
$string = preg_replace("/" . $quoteValue . "/iu", "<".$tag." class=".$cls.">$0".$tag.">", $string);
13. А так же заменяем строку
$text = preg_replace("/(\[\[\+.*?\]\])/i", "", $text);
$text = preg_replace("/(\[\[\+.*?\]\])/iu", "", $text);
14. И последнее, надо закомментировать строчку
if (!empty($str)) $this->searchString = strip_tags($this->modx->sanitizeString($str));
Основные чанки SimpleSearch
Поиск на сайте под управлением Modx Revolution готов. Он работает, можете убедиться в этом сами, но есть еще несколько моментов, которые пригодятся в работе с этим сниппетом. А именно редактирование чанков результатов поиска, его обертки, пагинации и так далее. Для начала Вам нужно понимать, что все чанки в формате.tpl находятся вот по этому пути: core/components/simplesearch/elements/chunks/. Ну а для того, чтобы с ними было легче работать выведем основные чанки в админку Modx. Вот их параметры
- containerTpl
- pageTpl
- currentPageTpl
Ну а называть сами чанки мы уже будем как хотим.
Параметр tpl - чанк SimpleSearchResult
Параметр tpl
отвечает за вывод каждого отдельного пункта результата поиска. Давайте создадим чанк и назовем его SimpleSearchResult
. Скопируем в него код из файла core/components/simplesearch/elements/chunks/searchresult.chunk.tpl
:
[[+idx]]. заменяем на
$text = preg_replace("/(\[\[\+.*?\]\])/iu", "", $text);
строку 311:
$text = trim(preg_replace("/\s+/", " ", $this->sanitize($text)));
заменяем на
$text = trim(preg_replace("/\s+/u", " ", $this->sanitize($text)));
строку 413:
$string = preg_replace("/" . $quoteValue . "/i", "<".$tag." class="".$cls."">$0".$tag.">", $string);
заменяем на
$string = preg_replace("/" . $quoteValue . "/iu", "<".$tag." class="".$cls."">$0".$tag.">", $string);
закоментируем строку 179:
If (!empty($str)) $this->searchString = strip_tags($this->modx->sanitizeString($str));
т.е. должно получиться вот так
/*if (!empty($str)) $this->searchString = strip_tags($this->modx->sanitizeString($str)); */
3. Делаем копии всех стандартных чанков
которые лежат в директории core/components/simplesearch/elements/chunks/
Создаем новые чанки с теми же именами и префиксом -new, и тем же содержимым (только они уже не на основе файлов, а обычные), для чего все это поймете дальше.
Например, берем первый чанк currentpagelink.chunk.tpl
и создаем новый чанк currentpagelink-new
(элементы — создать новый чанк) ну и переносим в него код.
[[+text]]
Отвечает за управления кнопкой в пагинации для активной страницы.
И таким же образом создаем остальные чанки:
— pagelink-new
— отвечает за вывод отдельной кнопки пагинации.
[[+text]]
- [[+link]]
- ссылка надокумент
- [[+text]]
- номер документа
— searchform-new
— форма поиска
— searchnoresults
можно не переносить — там нет не какого оформления;
— searchresult-new
— вывод каждого пункта результата.
[[+idx]]. [[+pagetitle]]
[[+extract]]
- [[+idx]]
- номер результата поиска в списке
- [[+link:is=``:then=`[[~[[+id]]]]`:else=`[[+link]]`]]
- [[+longtitle]]
- расширенный заголовок
- [[+pagetitle]]
- заголовок
- [[+extract]]
- текст, по которому был найден этот документ
— searchresultli
— по сути тоже можно не переносить.
— searchresults-new
— обертка всех результатов
[[+resultInfo]]
[[+paging]]
[[+results]]
[[%sisea.result_pages? &namespace=`sisea` &topic=`default`]][[+paging]]
- [[+resultInfo]]
- инф-я о кол-ве найденных документов и по какому словосочетанию.
- [[+sisea.result_pages? &namespace=`sisea` &topic=`default`]]
Вывод фразы «Страницы с результатами поиска:»
- [[+paging]]
- пагинация
- [[+results]]
- результаты поиска
После всего проделанного у вас должно получиться 5 новых чанков.
4. Создаем новый документ на который будут выводиться результаты поиска
Заголовок: Результаты поиска, ставим галку «Не показывать в меню». В «Настройки» и убираем галки с «Доступен для поиска», «Использовать HTML-редактор». Сохраняем. Обновляем страницу и прописываем в содержимое
[[!SimpleSearch? &tpl=`searchresult-new` &containerTpl=`searchresults-new` &pageTpl=`pagelink-new` ¤tPageTpl=`currentpagelink-new`]]
чанки оформлении которые создали на 3 шаге (внешний вид).
Если хотите чтобы в результах поиска были картинки, то дописываем в конце этого вывода
&includeTVs=`1` &processTVs=`1`
В чанке searchresult картинку можно вызывать так: [[+img]].
5. Выводим форму поиска
На месте где нужно вывести форму поиска, пишем
[[!SimpleSearchForm? &landing=`11` &tpl=`searchform-new`]]
Здесь landing — id страницы с результатами поиска, в tpl — чанки оформления формы, который создали на 3 шаге.
Делали 4 и 5 шаг мы для того, чтобы можно было редактировать на свое усмотрение внешнее оформление: самой формы, результатов поиска и т.д. не влезая в исходники. А стандартное оформление достаточно печальное, вот так к примеру выглядит стандартная форма поиска.
6. Меняем оформление.
Описывать как оформить все чанки не вижу смысла, для примера приведу новое оформление для чанка searchform-new
Это обычная стандартная разметка формы от бутстрап 3, на сайте выглядит так:
Официальная документация здесь: docs.modx.com/extras/revo/simplesearch
Если есть вопросы, пишите задавайте их в комментариях.
This snippet displays search results based on the search criteria sent.
Usage
Simply place the snippet in the Resource you would like to display search results in.
[[!SimpleSearch]]
Available Properties
Name
Description
Default
tpl
The chunk that will be used to display the contents of each search result.
SearchResult
containerTpl
The chunk that will be used to wrap all the search results, pagination and message.
SearchResults
useAllWords
If true, will only find results with all the specified search words.
0
maxWords
The maximum number of words to include in the search. Only applicable if useAllWords is off.
7
minChars
The minimum number of characters to trigger the search.
3
searchStyle
To search either with a "partial" LIKE search, or a relevance-based "match" search.
partial
andTerms
Whether or not to add a logical AND between words.
1
matchWildcard
Enable wildcard search. Set to false to do exact searching on a search term.
1
docFields
A comma-separated list of specific Resource fields to search.
pagetitle,longtitle,alias,description,introtext,content
fieldPotency
Score and sort the results (see https://github.com/splittingred/SimpleSearch/pull/29 for more infos/usage)
perPage
The number of search results to show per page.
10
showExtract
Whether or not to show an extract of the content of each search result.
1
extractSource
(new in version 1.9) Allows the user to define where the extract comes from. If the value of this parameter is a resource field name (including TVs if &includeTVs is set) then that resource field is used for the extract. Otherwise the parameter is taken as the name of a Snippet to run. The Snippet is passed the resource array as parameters. If there is no Snippet by that name, then the extract will be empty.
content
extractLength
The number of characters for the content extraction of each search result.
200
extractEllipsis
The string used to wrap extract results with. Defaults to an ellipsis.
...
includeTVs
Indicates if TemplateVar values should be included in the properties available to each resource template. Defaults to 0. Turning this on might make your search slower if you have lots of TVs.
0
includeTVList
An optional comma-delimited list of TemplateVar names to include explicitly if includeTVs is 1.
process TVs
Indicates if TemplateVar values should be rendered as they would on the resource being summarized. Defaults to 0. Some notes:
TVs can be accessed by their TV name [[+myTV]] By default SimpleSearch does not use a prefix, e.g. [[+tv.myTV]] will NOT render. TVs are processed during indexing for Solr searching, so there is no need to do this here.
0
highlightResults
Whether or not to highlight the search term in results.
1
highlightClass
The CSS class name to add to highlighted terms in results.
simplesearch-highlight
highlightTag
The html tag to wrap the highlighted term with in search results.
span
pageTpl
The chunk to use for a pagination link.
PageLink
currentPageTpl
The chunk to use for the current pagination link.
CurrentPageLink
pagingSeparator
The separator to use between pagination links.
ids
A comma-separated list of IDs to restrict the search to.
idType
The type of restriction for the ids parameter. If parents, will add all the children of the IDs in the ids parameter to the search. If documents, will only use the specified IDs in the search.
parents
exclude
A comma-separated list of resource IDs to exclude from search eg. "10,15,19". This will exclude the resources with the ID "10","15" or "19".
depth
If idtype is set to parents, the depth down the Resource tree that will be searched with the specified IDs.
10
hideMenu
Whether or not to return Resources that have hidemenu on. 0 shows only visible Resources, 1 shows only hidden Resources, 2 shows both.
2
contexts
The contexts to search. Defaults to the current context if none are explicitly specified.
searchIndex
The name of the REQUEST parameter that the search will use.
search
offsetIndex
The name of the REQUEST parameter to use for the pagination offset.
simplesearch_offset
placeholderPrefix
The prefix for global placeholders set by this snippet.
simplesearch.
toPlaceholder
Whether to set the output to directly return, or set to a placeholder with this propertys name.
urlScheme
The URL scheme you want: http, https, full, abs, relative, etc. See the $modx->makeUrl() documentation. This is used when the pagination links are generated.
customPackages
Set to search custom tables by loading their package. See below for more details.
postHooks
A comma-separated list of hooks to run that can add faceted sets to the end results.
activeFacet
The current active facet. Leave this alone unless you want a result to show from a non-standard facet derived through a postHook.
default
facetLimit
The number of non-active-facet results to show on the main results page.
5
sortBy
A comma-separated list of Resource fields to sort the results by. Leave blank to sort by relevance and score.
sortDir
A comma-separated list of directions to sort the results by. Must match the number of items in the sortBy parameter.
DESC
noResultsTpl
The chunk to use when no search results are found.
SimpleSearch Chunks
There are 4 chunks that are processed in SimpleSearch. Their corresponding SimpleSearch parameters are:
- tpl - The Chunk to use for each result displayed.
- containerTpl - The Chunk that will be used to wrap all the search results, pagination and message.
- pageTpl - The Chunk to use for a pagination link.
- currentPageTpl - The Chunk to use for the current pagination link.
Searching Custom Tables
Searching custom tables is available in SimpleSearch using the &customPackages property; however, you must have a custom package built for it. The format is:
ClassName:fieldName(s):packageName:packagePath:joinCriteria||class2Name:fieldName(s):package2Name:package2Path:join2Criteria
In other words, each custom package is separated by ||. Then, each part of it is separated by colons (:). An example to search Quip comments:
&customPackages=`quipComment:body:quip:{core_path}components/quip/model/:quipComment.resource = modResource.id`
Let"s break down each part:
- className
- The class name of the table you want to search. Here, it"s QuipComment.
- fieldName(s)
- A comma-separated list of column names to search. We did "body", you could also have done "body,email" or whatever.
- packageName
- The name of the schema Package to add. This one is called quip.
- packagePath
- The path to the model/ directory where the package is located.
- joinCriteria
- The SQL to join the table you want to search and the modResource table. Your table must have some connection to the Resource it"s on (otherwise SimpleSearch won"t know how to load a URL for it!)
Once you"ve added it, it will search those fields as well for data. If it finds it in that table, it will display the result as a link to the Resource you specified in your joinCriteria. In our example, that would be the resource the Quip comment is located on.
[[+idx]]. заменяем на
$text = preg_replace("/(\[\[\+.*?\]\])/iu", "", $text);
строку 311:
$text = trim(preg_replace("/\s+/", " ", $this->sanitize($text)));
заменяем на
$text = trim(preg_replace("/\s+/u", " ", $this->sanitize($text)));
строку 413:
$string = preg_replace("/" . $quoteValue . "/i", "<".$tag." class="".$cls."">$0".$tag.">", $string);
заменяем на
$string = preg_replace("/" . $quoteValue . "/iu", "<".$tag." class="".$cls."">$0".$tag.">", $string);
закоментируем строку 179:
If (!empty($str)) $this->searchString = strip_tags($this->modx->sanitizeString($str));
т.е. должно получиться вот так
/*if (!empty($str)) $this->searchString = strip_tags($this->modx->sanitizeString($str)); */
3. Делаем копии всех стандартных чанков
которые лежат в директории core/components/simplesearch/elements/chunks/
Создаем новые чанки с теми же именами и префиксом -new, и тем же содержимым (только они уже не на основе файлов, а обычные), для чего все это поймете дальше.
Например, берем первый чанк currentpagelink.chunk.tpl
и создаем новый чанк currentpagelink-new
(элементы — создать новый чанк) ну и переносим в него код.
[[+text]]
Отвечает за управления кнопкой в пагинации для активной страницы.
И таким же образом создаем остальные чанки:
— pagelink-new
— отвечает за вывод отдельной кнопки пагинации.
[[+text]]
- [[+link]]
- ссылка надокумент
- [[+text]]
- номер документа
— searchform-new
— форма поиска
— searchnoresults
можно не переносить — там нет не какого оформления;
— searchresult-new
— вывод каждого пункта результата.
[[+idx]]. [[+pagetitle]]
[[+extract]]
- [[+idx]]
- номер результата поиска в списке
- [[+link:is=``:then=`[[~[[+id]]]]`:else=`[[+link]]`]]
- [[+longtitle]]
- расширенный заголовок
- [[+pagetitle]]
- заголовок
- [[+extract]]
- текст, по которому был найден этот документ
— searchresultli
— по сути тоже можно не переносить.
— searchresults-new
— обертка всех результатов
[[+resultInfo]]
[[+paging]]
[[+results]]
[[%sisea.result_pages? &namespace=`sisea` &topic=`default`]][[+paging]]
- [[+resultInfo]]
- инф-я о кол-ве найденных документов и по какому словосочетанию.
- [[+sisea.result_pages? &namespace=`sisea` &topic=`default`]]
Вывод фразы «Страницы с результатами поиска:»
- [[+paging]]
- пагинация
- [[+results]]
- результаты поиска
После всего проделанного у вас должно получиться 5 новых чанков.
4. Создаем новый документ на который будут выводиться результаты поиска
Заголовок: Результаты поиска, ставим галку «Не показывать в меню». В «Настройки» и убираем галки с «Доступен для поиска», «Использовать HTML-редактор». Сохраняем. Обновляем страницу и прописываем в содержимое
[[!SimpleSearch? &tpl=`searchresult-new` &containerTpl=`searchresults-new` &pageTpl=`pagelink-new` ¤tPageTpl=`currentpagelink-new`]]
чанки оформлении которые создали на 3 шаге (внешний вид).
Если хотите чтобы в результах поиска были картинки, то дописываем в конце этого вывода
&includeTVs=`1` &processTVs=`1`
В чанке searchresult картинку можно вызывать так: [[+img]].
5. Выводим форму поиска
На месте где нужно вывести форму поиска, пишем
[[!SimpleSearchForm? &landing=`11` &tpl=`searchform-new`]]
Здесь landing — id страницы с результатами поиска, в tpl — чанки оформления формы, который создали на 3 шаге.
Делали 4 и 5 шаг мы для того, чтобы можно было редактировать на свое усмотрение внешнее оформление: самой формы, результатов поиска и т.д. не влезая в исходники. А стандартное оформление достаточно печальное, вот так к примеру выглядит стандартная форма поиска.
6. Меняем оформление.
Описывать как оформить все чанки не вижу смысла, для примера приведу новое оформление для чанка searchform-new
Это обычная стандартная разметка формы от бутстрап 3, на сайте выглядит так:
Официальная документация здесь: docs.modx.com/extras/revo/simplesearch
Если есть вопросы, пишите задавайте их в комментариях.
This snippet displays search results based on the search criteria sent.
Usage
Simply place the snippet in the Resource you would like to display search results in.
[[!SimpleSearch]]
Available Properties
[[+idx]]. [[+pagetitle]]
[[+extract]]
Вывод фразы «Страницы с результатами поиска:»
Name | Description | Default |
---|---|---|
tpl | The chunk that will be used to display the contents of each search result. | SearchResult |
containerTpl | The chunk that will be used to wrap all the search results, pagination and message. | SearchResults |
useAllWords | If true, will only find results with all the specified search words. | 0 |
maxWords | The maximum number of words to include in the search. Only applicable if useAllWords is off. | 7 |
minChars | The minimum number of characters to trigger the search. | 3 |
searchStyle | To search either with a "partial" LIKE search, or a relevance-based "match" search. | partial |
andTerms | Whether or not to add a logical AND between words. | 1 |
matchWildcard | Enable wildcard search. Set to false to do exact searching on a search term. | 1 |
docFields | A comma-separated list of specific Resource fields to search. | pagetitle,longtitle,alias,description,introtext,content |
fieldPotency | Score and sort the results (see https://github.com/splittingred/SimpleSearch/pull/29 for more infos/usage) | |
perPage | The number of search results to show per page. | 10 |
showExtract | Whether or not to show an extract of the content of each search result. | 1 |
extractSource | (new in version 1.9) Allows the user to define where the extract comes from. If the value of this parameter is a resource field name (including TVs if &includeTVs is set) then that resource field is used for the extract. Otherwise the parameter is taken as the name of a Snippet to run. The Snippet is passed the resource array as parameters. If there is no Snippet by that name, then the extract will be empty. | content |
extractLength | The number of characters for the content extraction of each search result. | 200 |
extractEllipsis | The string used to wrap extract results with. Defaults to an ellipsis. | ... |
includeTVs | Indicates if TemplateVar values should be included in the properties available to each resource template. Defaults to 0. Turning this on might make your search slower if you have lots of TVs. | 0 |
includeTVList | An optional comma-delimited list of TemplateVar names to include explicitly if includeTVs is 1. | |
process TVs | Indicates if TemplateVar values should be rendered as they would on the resource being summarized. Defaults to 0. Some notes: TVs can be accessed by their TV name [[+myTV]] By default SimpleSearch does not use a prefix, e.g. [[+tv.myTV]] will NOT render. TVs are processed during indexing for Solr searching, so there is no need to do this here. |
0 |
highlightResults | Whether or not to highlight the search term in results. | 1 |
highlightClass | The CSS class name to add to highlighted terms in results. | simplesearch-highlight |
highlightTag | The html tag to wrap the highlighted term with in search results. | span |
pageTpl | The chunk to use for a pagination link. | PageLink |
currentPageTpl | The chunk to use for the current pagination link. | CurrentPageLink |
pagingSeparator | The separator to use between pagination links. | |
ids | A comma-separated list of IDs to restrict the search to. | |
idType | The type of restriction for the ids parameter. If parents, will add all the children of the IDs in the ids parameter to the search. If documents, will only use the specified IDs in the search. | parents |
exclude | A comma-separated list of resource IDs to exclude from search eg. "10,15,19". This will exclude the resources with the ID "10","15" or "19". | |
depth | If idtype is set to parents, the depth down the Resource tree that will be searched with the specified IDs. | 10 |
hideMenu | Whether or not to return Resources that have hidemenu on. 0 shows only visible Resources, 1 shows only hidden Resources, 2 shows both. | 2 |
contexts | The contexts to search. Defaults to the current context if none are explicitly specified. | |
searchIndex | The name of the REQUEST parameter that the search will use. | search |
offsetIndex | The name of the REQUEST parameter to use for the pagination offset. | simplesearch_offset |
placeholderPrefix | The prefix for global placeholders set by this snippet. | simplesearch. |
toPlaceholder | Whether to set the output to directly return, or set to a placeholder with this propertys name. | |
urlScheme | The URL scheme you want: http, https, full, abs, relative, etc. See the $modx->makeUrl() documentation. This is used when the pagination links are generated. | |
customPackages | Set to search custom tables by loading their package. See below for more details. | |
postHooks | A comma-separated list of hooks to run that can add faceted sets to the end results. | |
activeFacet | The current active facet. Leave this alone unless you want a result to show from a non-standard facet derived through a postHook. | default |
facetLimit | The number of non-active-facet results to show on the main results page. | 5 |
sortBy | A comma-separated list of Resource fields to sort the results by. Leave blank to sort by relevance and score. | |
sortDir | A comma-separated list of directions to sort the results by. Must match the number of items in the sortBy parameter. | DESC |
noResultsTpl | The chunk to use when no search results are found. |
SimpleSearch Chunks
There are 4 chunks that are processed in SimpleSearch. Their corresponding SimpleSearch parameters are:
- tpl - The Chunk to use for each result displayed.
- containerTpl - The Chunk that will be used to wrap all the search results, pagination and message.
- pageTpl - The Chunk to use for a pagination link.
- currentPageTpl - The Chunk to use for the current pagination link.
Searching Custom Tables
Searching custom tables is available in SimpleSearch using the &customPackages property; however, you must have a custom package built for it. The format is:
ClassName:fieldName(s):packageName:packagePath:joinCriteria||class2Name:fieldName(s):package2Name:package2Path:join2Criteria
In other words, each custom package is separated by ||. Then, each part of it is separated by colons (:). An example to search Quip comments:
&customPackages=`quipComment:body:quip:{core_path}components/quip/model/:quipComment.resource = modResource.id`
Let"s break down each part:
- className - The class name of the table you want to search. Here, it"s QuipComment.
- fieldName(s) - A comma-separated list of column names to search. We did "body", you could also have done "body,email" or whatever.
- packageName - The name of the schema Package to add. This one is called quip.
- packagePath - The path to the model/ directory where the package is located.
- joinCriteria - The SQL to join the table you want to search and the modResource table. Your table must have some connection to the Resource it"s on (otherwise SimpleSearch won"t know how to load a URL for it!)
Once you"ve added it, it will search those fields as well for data. If it finds it in that table, it will display the result as a link to the Resource you specified in your joinCriteria. In our example, that would be the resource the Quip comment is located on.