latest
  • User Guide
  • Developer Guide
  • Cookbooks
    • Create a custom action
    • Create a custom filter
    • Create a custom model
    • Custom pivots
    • Create a custom tag
    • Custom search
    • Pivot Templates
    • Writing your own module
    • Overriding Zotonic
    • Execute tasks asynchronously using the task queue
    • Icons in templates
    • Logging to Logstash
    • How to customise error pages
    • Exometer metrics
    • Frontend cookbook
    • Admin cookbook
    • Shell cookbook
    • Just enough...
  • Best Practices
  • Reference
  • Glossary
Zotonic
  • Docs »
  • Cookbooks »
  • Custom search
  • Edit on GitHub

Custom search¶

Implement a custom search by observing the search_query notification in your module. Imagine you want to search cookies in your database that either have chocolate or do not:

-include_lib("zotonic_core/include/zotonic.hrl").

-export([
    observe_search_query/2
]).

observe_search_query(#search_query{search = Search, offsetlimit = OffsetLimit}, Context) ->
    %% Pass on to an internal function.
    search(Search, OffsetLimit, Context).

search({cookies, [{chocolate, Boolean}]}, _OffsetLimit, Context)
    %% Handle search queries of the cookie type.
    #search_sql{
        select="c.id",
        from="foo c",
        where="c.chocolate = $1",
        order="c.name desc",
        args=[Boolean],
        tables=[{cookies_table, "c"}]
    };
search(_Other, _OffsetLimit, _Context) ->
    %% Let other modules handle other types of search queries.
    undefined.

Do not forget to add the last function that matches and returns undefined for any other search request. If you forget this, the notification fold will crash when using any other search query.

This can then be used in your template like this:

{% for id in m.search[{cookies chocolate=true}] %}
    Looping over all ids in the ‘cookies_table’ table for which chocolate = true
{% endfor %}
Next Previous

© Copyright 2009–2017, The Zotonic Project (zotonic.com). Revision 727298a2.

Built with Sphinx using a theme provided by Read the Docs.
Read the Docs v: latest
Versions
latest
stable
0.x
Downloads
pdf
htmlzip
epub
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.