Change theme:   

Search over elements

If you have a quite long list of books on your site and you want to make it easier for the user to find a certain book, then the ability to search through Edicy elements comes in handy.

For example you could choose either the category or the author of the book and search for matching items:


There are a few limitations and preconditions for creating a search through elements:

  • searching through elements works on 1:1 and n:1 relations; it can't be used with 1:n and n:n relations,
  • the search page should be of type Elements, otherwise the search won't work.

The code for creating the search form:

<form action="#search-results" id="element-search-form" method="get">
    <select name="element[author]">
        <option value="">(Choose author)</option>
        {% elementscontext %}
            {% for element in elements %}
                <option value="{{ element.author }}">{{ element.author }}</option>
        {% endfor %}
    {% endelementscontext %}
    </select>
    <select name="element[category]">
        <option value="">(Choose category)</option>
        <option value="Children's">Children's</option>
        <option value="Philosophy">Philosophy</option>
        <option value="Fiction">Fiction</option>
        <option value="Travel">Travel</option>
    </select>                
    <input type="hidden" name="search" value="1" />
    <input type="hidden" name="search_type" value="Book" />
    <input type="hidden" name="search_path_prefix" value="path/to/books/page" />
    <button id="search-elements">Search</button>
</form>

To make the search work, some JavaScript code is needed (form and button IDs are used to initiate the search):

$('#search-elements').click(function(event) {
    event.preventDefault();
    $('#element-search-form').submit();
});

Search can have some additional parameters:

  • search - required for the search to work
    <input type="hidden" name="search" value="1" />
  • search_type - the name of the element definition
  • search_type_id - the ID of the element definition
  • search_path - searches elements from exact page path
  • search_path_prefix - searches elements from page path and all of the page's children pages
  • search_all_languages - search across all languages. By default only elements in current language are searched.

The code for displaying search results:

{% if searched_elements %}
    <div id="search-results">
        <h2>Search results</h2>
        {% if searched_elements.size > 0 %}
            <ul>
                {% for element in searched_elements %}
                <li>{{ element.title }} by {{ element.author }}</li>     
                {% endfor %}
            </ul>
        {% else %}
            <p>No results found!</p>
        {% endif %}
    </div>
{% endif %}

searched_elements is created automatically by Edicy.