Define filters or search fields in CodeIgniter 4

- Andrés Cruz

En español
Define filters or search fields in CodeIgniter 4

Filters are a very useful tool in web development as they allow users to search, sort and filter information efficiently. Filters can be used to sort and classify data in a table or list and access the desired information without having to search through large amounts of data. Let's see how to implement a simple filter in CodeIgniter 4.

In CodeIgniter 4, as in many frameworks, it's very easy to create filter-like functions; in this case it is through a text type field; so for this, we are going to create a field like the following:

<input type="text" name="search" placeholder="search" value="<?= $search ?>">

Which is part of our complete formulary:

<form method="get" id="formFilter">
    <select name="type">
        <option value="">Tipos</option>
        <option <?= ($typeId == "exit") ? "selected" : "" ?> value="exit">Salida</option>
        <option <?= ($typeId == "entry") ? "selected" : "" ?> value="entry">Entrada</option>
    </select>
    <select name="user_id">
        <option value="">Usuarios</option>
        <?php foreach ($users as $u) : ?>
            <option <?= ($u->id == $userId) ? "selected" : "" ?> value="<?= $u->id ?>"><?= $u->username ?></option>
        <?php endforeach ?>
    </select>
    <br>
    <h4>Búsqueda</h4>
    <input value="<?= $search ?>" type="text" name="search" placeholder="Buscar">
    <h3>Cantidades</h3>
    <label for="check_cant">
        Activar
        <input type="checkbox" name="check_cant" id="check_cant" checked>
    </label>
    <br>
    <label for="min_cant">
        Minimo <span><?= $minCant ? $minCant : 0 ?></span>:
        <input type="range" name="min_cant" value="<?= $minCant ? $minCant : 0 ?>" min="0" max="90" step="1">
    </label>
    <br>
    <label for="max_cant">
        Maximo <span><?= $maxCant ? $maxCant : 100 ?></span>:
        <input type="range" name="max_cant" value="<?= $maxCant ? $maxCant : 100 ?>" min="10" max="100" step="1">
    </label>
    <br>
    <button type="submit">Enviar</button>
    <a href="<?= route_to('product.trace',$product->id) ?>">Limpiar</a>
</form>

In which you can place other fields of any type for your filters; which we do in the full CodeIgniter 4 course; these fields at the end are nothing more than those used in the forms to perform any other saving or editing operation, we have the SELECT and text fields but you can use others such as CHECKBOX or RADIUS if you consider them necessary.

But that is another story; note that the action of the form is not defined, which means that when sending the request it will be processed by the same page that paints the search form; in the case of the course, it is a list of product details.

Whose filter, as you can see in the previous form, is processed by the same controller that processes the previous table; In our controller, to know if we are going to process any search data, we ask from the filter:

   $searchs = explode(" ", trim($this->request->getGet('search')));
        if ($this->request->getGet('search')) {
            //->orGroupStart()
            $query->groupStart();
            foreach ($searchs as $s) {
                $query->orLike('u.username', $s)
                    ->orLike('u.email', $s)
                    ->orLike('puc.description', $s);
            }
            $query->groupEnd();

Here are several aspects that you have to take into account:

  • We use the explode function to search for tokens.
  • We iterate the tokens and search for partial matches with the like on the columns we want to search for; in our case, a username, email and description that make sure they belong to different tables.

Since we are using OR operations, it is possible that they interfere with other where or similar filters in the rest of the query; therefore, we group them (in SQL we put them in parentheses) so that they only affect the section of the search with the groupStart and groupEnd

In essence all of the above steps are optional and depending on your needs you may want to search for exact matches; if that's the case, you just need to define it as:

$query->where('u.username', $this->request->getGet('search'))

To find an exact match on the username column.

You can see the complete code in case you have doubts

https://github.com/libredesarrollo/codeigniter4-inventario/blob/main/app/Controllers/Dashboard/Product.php

The important thing here is to note that we are building the query to tokens or pieces, in which we ask through a conditional if we have data received by the user and with this we build the query; as in our example is a lookup field that we want to build

Filtro ejemplo
Filtro ejemplo
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.