Search on ContentType listing page

Often times people are looking to create a simple search on the listing page (for example, to search blog posts, news, events, etc.). In this article, I'll share how to do that easy-peasy in twig itself.

Let's assume that we have a listing page /events for a ContentType with the following definition:

    name: Events
    singular_name: Event
            type: text
            type: image
            type: html
    listing_template: events_listing.twig

By default, the events_listing.twig file will contain a records variable, which is an array of all published events. What we will do in this article is this:

  • create a form with a search field, that when submitted, goes to `/events?search=apples
  • in our events_listing.twig, we will only display those records that mention the search term apples, so that when the listing is displayed, it shows those relevant results.

Let's build the search form

Locate your events_listing.twig file and, at a place of your own choosing, put the following code:

<form action="" method="get">
    <input type="search" name="search" />
    <button type="submit">Hit me to search</button>

Now, if you go to /events in the browser, enter apples in the search box and press "Hit me to search", the page will reload. After the reload, the URL in the address bar will be /events?search=apples. Great!

Fetch the records containing the search word

To make the search work, we have two final steps. First, get the search word and then, use the setcontent tag to update the records to only include the ones that match it. Here is how to do it:

{% set searchTerm = app.request.get('search') %}
{% if searchTerm|trim is not empty %}
    {# we have a search! #}
    {% setcontent records =  contenttype.slug where { 'anyField': '%' ~ searchTerm ~ '%' } %}
{% endif %}

Note: The code above will override the records variable. If you use the named array for the ContentType, e.g. events in your twig template, then make sure to override this instead. Also, make sure to override it at the top of the template before it is used to display the content.

Prepopulate input field with search

The above example works perfectly fine, but if you search for a term, e.g. 'apples', once you press the "Hit me to search" button, the input field will clear. To keep the input field in tact with what is being searched, make sure to:

Move the following piece of code before the input field:

{% set searchTerm = app.request.get('search') %}

Then, update the HTML input element as follows:

<input type="search" name="search" value="{{ searchTerm }}" />

That's it! Happy searching. 🤠

Search ContentTypes

Permalink - Written by Ivo on June 8, 2020.

« Setting up a local development environment - Phone number validation »