CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

CakeDC Search Filter Plugin

This article is part of the CakeDC Advent Calendar 2024 (December 21th 2024)

The CakeDC Search Filter plugin is a powerful tool for CakePHP applications that provides advanced search functionality with a modern, user-friendly interface. It combines backend flexibility with a Vue.js-powered frontend to create dynamic search filters. Key features include:

  • Dynamic filter generation based on database schema
  • Multiple filter types for different data types
  • Customizable search conditions
  • Interactive Vue.js frontend
  • AJAX-powered autocomplete functionality
  • Seamless integration with CakePHP's ORM

Setup

  1. Install the plugin using Composer:

    composer require cakedc/search-filter
  2. Load the plugin in your application's src/Application.php:

    $this->addPlugin('CakeDC/SearchFilter');
  3. Add the search element to your view inside search form:

    <?= $this->element('CakeDC/SearchFilter.Search/v_search'); ?>
  4. Initialize the Vue.js application:

    <script>
    window._search.createMyApp(window._search.rootElemId)
    </script>

Filters

Filters are the user interface elements that allow users to interact with the search. The plugin provides several built-in filter types for different data scenarios:

  1. BooleanFilter: For Yes/No selections

    $booleanFilter = (new BooleanFilter())
       ->setCriterion(new BoolCriterion('is_active'))
       ->setLabel('Active Status')
       ->setOptions([1 => 'Active', 0 => 'Inactive']);
  2. DateFilter: For date-based filtering

    $dateFilter = (new DateFilter())
       ->setCriterion(new DateCriterion('created_date'))
       ->setLabel('Creation Date')
       ->setDateFormat('YYYY-MM-DD');
  3. StringFilter: For text-based searches

    $stringFilter = (new StringFilter())
       ->setCriterion(new StringCriterion('title'))
       ->setLabel('Title');
  4. NumericFilter: For number-based filtering

    $numericFilter = (new NumericFilter())
       ->setCriterion(new NumericCriterion('price'))
       ->setLabel('Price')
       ->setProperty('step', '0.01');
  5. LookupFilter: For autocomplete-based filtering

    $lookupFilter = (new LookupFilter())
       ->setCriterion(new LookupCriterion('user_id', $usersTable, new StringCriterion('name')))
       ->setLabel('User')
       ->setLookupFields(['name', 'email'])
       ->setAutocompleteRoute(['controller' => 'Users', 'action' => 'autocomplete']);
  6. MultipleFilter: For selecting multiple values

    $multipleFilter = (new MultipleFilter())
       ->setCriterion(new InCriterion('category_id', $categoriesTable, new StringCriterion('name')))
       ->setLabel('Categories')
       ->setProperty('placeholder', 'Select multiple options');
  7. SelectFilter: For dropdown selections

    $selectFilter = (new SelectFilter())
       ->setCriterion($manager->criterion()->numeric('status_id'))
       ->setLabel('Status')
       ->setOptions($this->Statuses->find('list')->toArray())
       ->setEmpty('All Statuses');

Criteria Purpose and Usage

Criteria are the building blocks that define how filters operate on your data. They handle the actual query building and data filtering. Key criterion types include:

  1. AndCriterion: Combines multiple criteria with AND logic
  2. BoolCriterion: Handles boolean comparisons
  3. StringCriterion: Handles string matching
  4. DateCriterion: Manages date comparisons
  5. DateTimeCriterion: Manages datetime comparisons
  6. InCriterion: Handles in comparisons
  7. LookupCriterion: Handles lookup comparisons
  8. NumericCriterion: Handles numeric comparisons
  9. OrCriterion: Combines multiple criteria with OR logic

Example of combining criteria:

$complexCriterion = new OrCriterion([
    new StringCriterion('title'),
    new StringCriterion('content')
]);

Filters Usage

Let's walk through a complete example of setting up filters in a controller. This implementation demonstrates how to integrate search filters with our htmx application from previous articles.

Figure 1-1

Controller Setup

First, we need to initialize the PlumSearch filter component in our controller:

public function initialize(): void
{
    parent::initialize();
    $this->loadComponent('PlumSearch.Filter');
}

Implementing Search Filters

Here's a complete example of setting up filters in the controller's list method:

// /src/Controller/PostsController.php
protected function list()
{
    $query = $this->Posts->find();

    $manager = new Manager($this->request);
    $collection = $manager->newCollection();

    $collection->add('search', $manager->filters()
        ->new('string')
        ->setConditions(new \stdClass())
        ->setLabel('Search...')
    );

    $collection->add('name', $manager->filters()
        ->new('string')
        ->setLabel('Name')
        ->setCriterion(
            new OrCriterion([
                $manager->buildCriterion('title', 'string', $this->Posts),
                $manager->buildCriterion('body', 'string', $this->Posts),
            ])
        )
    );

    $collection->add('created', $manager->filters()
        ->new('datetime')
        ->setLabel('Created')
        ->setCriterion($manager->buildCriterion('created', 'datetime', $this->Posts))
    );

    $viewFields = $collection->getViewConfig();

    if (!empty($this->getRequest()->getQuery()) && !empty($this->getRequest()->getQuery('f'))) {
        $search = $manager->formatSearchData();
        $this->set('values', $search);

        $this->Posts->addFilter('search', [
            'className' => 'Multiple',
            'fields' => [
                'title', 'body',
            ]
        ]);
        $this->Posts->addFilter('multiple', [
            'className' => 'CakeDC/SearchFilter.Criteria',
            'criteria' => $collection->getCriteria(),
        ]);

        $filters = $manager->formatFinders($search);
        $query = $query->find('filters', params: $filters);
    }

    $this->set('viewFields', $viewFields);

    $posts = $this->paginate($this->Filter->prg($query), ['limit' => 12]);
    $this->set(compact('posts'));
}

Table Configuration

Enable the filterable behavior in your table class:

// /src/Model/Table/PostsTable.php
public function initialize(array $config): void
{
    // ...
    $this->addBehavior('PlumSearch.Filterable');
}

View Implementation

In your view template, add the necessary assets and initialize the search filter:

<!-- templates/Posts/index.php -->
<?= $this->Html->css('CakeDC/SearchFilter.inline'); ?>
<?= $this->Html->script('CakeDC/SearchFilter.vue3.js'); ?>
<?= $this->Html->script('CakeDC/SearchFilter.main.js', ['type' => 'module']); ?>
<?= $this->element('CakeDC/SearchFilter.Search/v_templates'); ?>

<div id="search">
    <?= $this->Form->create(null, [
        'id' => 'search-form',
        'type' => 'get',
        'hx-get' => $this->Url->build(['controller' => 'Posts', 'action' => 'index']),
        'hx-target' => "#posts",
    ]); ?>
    <div id="ext-search"></div>
    <?= $this->Form->button('Search', ['type' => 'submit', 'class' => 'btn btn-primary']); ?>
    <?= $this->Form->end(); ?>
</div>

<script>
    window._search = window._search || {};
    window._search.fields = <?= json_encode($viewFields) ?>;
    var values = null;
    <?php if (!empty($values)): ?>
        window._search.values = <?= json_encode($values) ?>;
    <?php else: ?>
        window._search.values = {};
    <?php endif; ?>
</script>

JavaScript Integration

Finally, add the necessary JavaScript to handle the search filter initialization and htmx interactions:

<!-- /templates/Posts/index.php -->
<script>
function setupTable(reload) {
    if (reload) {
        setTimeout(function () {
            window._search.app.unmount()
            window._search.createMyApp(window._search.rootElemId)
        }, 20);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    window._search.createMyApp(window._search.rootElemId)
    setupTable(false);
    htmx.on('htmx:afterRequest', (evt) => {
        setupTable(true);
    })
});
</script>

The combination of CakePHP's search filter plugin with htmx provides a modern, responsive search experience with minimal JavaScript code.

Frontend Vue App Widgets

The plugin provides several Vue.js widgets for different filter types:

  • SearchInput: For basic text input
  • SearchInputNumericRange: For basic text input
  • SearchSelect, Select2, SearchSelectMultiple: For dropdown selections
  • SearchInputDate, SearchInputDateRange: For date picking
  • SearchInputDateTime, SearchInputDateTimeRange: For datetime picking
  • SearchLookupInput: For autocomplete functionality
  • SearchMultiple: For multiple selections
  • SearchSelectMultiple: For multiple selections

These widgets are automatically selected based on the filter type you define in your controller.

Custom Filters and Custom Widgets

The CakeDC Search Filter plugin can be extended with custom filters and widgets. Let's walk through creating a custom range filter that allows users to search between two numeric values.

Custom Filter Class

First, create a custom filter class that extends the AbstractFilter:

// /src/Controller/Filter/RangeFilter.php
<?php
declare(strict_types=1);

namespace App\Controller\Filter;

use Cake\Controller\Controller;
use CakeDC\SearchFilter\Filter\AbstractFilter;

class RangeFilter extends AbstractFilter
{
    protected array $properties = [
        'type' => 'range',
    ];

    protected object|array|null $conditions = [
        self::COND_BETWEEN => 'Between',
    ];
}

Custom Criterion Implementation

Create a criterion class to handle the range filtering logic:

// /src/Model/Filter/Criterion/RangeCriterion.php
<?php
declare(strict_types=1);

namespace App\Model\Filter\Criterion;

use Cake\Database\Expression\QueryExpression;
use Cake\ORM\Query;
use CakeDC\SearchFilter\Filter\AbstractFilter;
use CakeDC\SearchFilter\Model\Filter\Criterion\BaseCriterion;

class RangeCriterion extends BaseCriterion
{
    protected $field;

    public function __construct($field)
    {
        $this->field = $field;
    }

    public function __invoke(Query $query, string $condition, array $values, array $criteria, array $options): Query
    {
        $filter = $this->buildFilter($condition, $values, $criteria, $options);
        if (!empty($filter)) {
            return $query->where($filter);
        }

        return $query;
    }

    public function buildFilter(string $condition, array $values, array $criteria, array $options = []): ?callable
    {
        return function (QueryExpression $exp) use ($values) {
            if (!empty($values['from']) && !empty($values['to'])) {
                return $exp->between($this->field, $values['from'], $values['to']);
            }
            return $exp;
        };
    }

    public function isApplicable($value, string $condition): bool
    {
        return !empty($value['from']) || !empty($value['to']);
    }
}

Controller Integration

Update your controller to use the custom range filter:

// /src/Controller/PostsController.php
protected function list()
{
    // ...

    $manager = new Manager($this->request);
    $manager->filters()->load('range', ['className' => RangeFilter::class]);
    $collection = $manager->newCollection();

    $collection->add('id', $manager->filters()
        ->new('range')
        ->setLabel('Id Range')
        ->setCriterion($manager->buildCriterion('id', 'integer', $this->Posts))
    );

    // ...
}

Custom Vue.js Widget

Create a custom Vue.js component for the range input. It consists of two parts, widget template and widget component:

<!-- /templates/Posts/index.php -->
<script type="text/x-template" id="search-input-range-template">
  <span class="range-wrapper d-flex">
    <input
      type="number"
      class="form-control value value-from"
      :name="'v[' + index + '][from][]'"
      v-model="fromValue"
      @input="updateValue"
      :placeholder="field.fromPlaceholder || 'From'"
    />
    <span class="range-separator d-flex align-items-center">&nbsp;&mdash;&nbsp;</span>
    <input
      type="number"
      class="form-control value value-to"
      :name="'v[' + index + '][to][]'"
      v-model="toValue"
      @input="updateValue"
      :placeholder="field.toPlaceholder || 'To'"
    />
  </span>
</script>

<script>
const RangeInput = {
  template: "#search-input-range-template",
  props: ['index', 'value', 'field'],
  data() {
    return {
      fromValue: '',
      toValue: '',
    };
  },
  methods: {
    updateValue() {
      this.$emit('change-value', {
        index: this.index,
        value: {
          from: this.fromValue,
          to: this.toValue
        }
      });
    }
  },
  mounted() {
    if (this.value) {
      this.fromValue = this.value.from || '';
      this.toValue = this.value.to || '';
    }
  },
  watch: {
    value(newValue) {
      if (newValue) {
        this.fromValue = newValue.from || '';
        this.toValue = newValue.to || '';
      } else {
        this.fromValue = '';
        this.toValue = '';
      }
    }
  }
};
<script>

Component Registration

Register the custom widget in the Vue.js app. Implement the register function to register the custom widget, and the setupTable function to setup the table after a htmx request.

// /templates/Posts/index.php
function register(app, registrator) {
    app.component('RangeInput', RangeInput);
    registrator('range', function(cond, type) { return 'RangeInput';});
}

function setupTable(reload) {
    if (reload) {
        setTimeout(function () {
            window._search.app.unmount()
            window._search.createMyApp(window._search.rootElemId, register)
        }, 20);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    window._search.createMyApp(window._search.rootElemId, register)
    setupTable(false);
    htmx.on('htmx:afterRequest', (evt) => {
        setupTable(true);
    })
});
</script>

This implementation creates a custom range filter that allows users to search for records within a specified numeric range. The filter consists of three main components:

  1. A custom filter class (RangeFilter) that defines the filter type and conditions
  2. A custom criterion class (RangeCriterion) that implements the filtering logic
  3. A Vue.js component (RangeInput) that provides the user interface for entering range values
  4. A registration function to register the custom widget, and the setupTable function to setup the table after a htmx request.

Demo Project for Article

The examples used in this article are located at https://github.com/skie/cakephp-htmx/tree/4.0.0 and available for testing.

Conclusion

The CakeDC Search Filter plugin provides a robust solution for implementing advanced search functionality in CakePHP applications. Its combination of flexible backend filtering and modern frontend components makes it an excellent choice for any CakePHP project. The plugin's extensibility allows for customization to meet specific project needs, while its built-in features cover most common search scenarios out of the box.

Whether you need simple text searches or complex multi-criteria filtering, the Search Filter plugin offers the tools to build user-friendly search interfaces.

This article is part of the CakeDC Advent Calendar 2024 (December 21th 2024)

Latest articles

Goodbye to 2025!

Well bakers… another advent calendar is coming to an end. I hope you enjoyed all of the topics covered each day. We are also closing the year with so much gratitude.    2025 was the 20th year of CakePHP, can you believe it? We had an amazing year with our team, the community and the CakePHP core. It was great connecting with those who attended CakeFest in Madrid, and we hope to have the opportunity to see more of you in 2026.    I cannot let the year end without getting a little sentimental. There is no better way to say it… THANK YOU. Thank you to the team who worked so hard, the core team that keeps pumping out releases, and most of all … thank you to our clients that trust us with their projects. CakeDC is successful because of the strong relationships we build with our network, and we hope to continue working with all of you for many years.    There are a lot of great things still to come in year 21! Could 2026 will be bringing us CakePHP 6?! Considering 2 is rhe legal drinking age in the US, maybe CakePHP 6 should be beer cake? Delicious. Stay tuned to find out.    Before I go, I am leaving you with something special. A note from Larry!   As we close out this year, I just want to say thank you from the bottom of my heart. Twenty years ago, CakePHP started as a simple idea shared by a few of us who wanted to make building on the web easier and more enjoyable. Seeing how far it has come, and more importantly, seeing how many lives and careers it has impacted, is something I never take for granted. I am deeply grateful for our team, the core contributors, the community, and our clients who continue to believe in what we do. You are the reason CakePHP and CakeDC are still here, still growing, and still relevant after two decades. Here is to what we have built together, and to what is still ahead. Thank you for being part of this journey. Larry

Pagination of multiple queries in CakePHP

Pagination of multiple queries in CakePHP

A less typical use case for pagination in an appication is the need to paginate multiples queries. In CakePHP you can achieve this with pagination scopes.

Users list

Lest use as an example a simple users list. // src/Controller/UsersController.php class UsersController extends AppController { protected array $paginate = [ 'limit' => 25, ]; public function index() { // Default model pagination $this->set('users', $this->paginate($this->Users)); } } // templates/Users/index.php <h2><?= __('Users list') ?>/h2> <table> <thead> <tr> <th><?= $this->Paginator->sort('name', __('Name')) ?></th> <th><?= $this->Paginator->sort('email', __('Email')) ?></th> <th><?= $this->Paginator->sort('active', __('Active')) ?></th> </tr> </thead> <tbody> <?php foreach ($users as $user): ?> <tr> <td><?= h($user->name) ?></td> <td><?= h($user->email) ?></td> <td><?= $user->active ? 'Yes' : 'No' ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?= $this->Paginator->counter() ?> <?= $this->Paginator->prev('« Previous') ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next('Next »') ?>

Pagination of multiple queries

Now, we want to display two paginated tables, one with the active users and the other with the inactive ones. // src/Controller/UsersController.php class UsersController extends AppController { protected array $paginate = [ 'Users' => [ 'scope' => 'active_users', 'limit' => 25, ], 'InactiveUsers' => [ 'scope' => 'inactive_users', 'limit' => 10, ], ]; public function index() { $activeUsers = $this->paginate( $this->Users->find()->where(['active' => true]), [scope: 'active_users'] ); // Load an additional table object with the custom alias set in the paginate property $inactiveUsersTable = $this->fetchTable('InactiveUsers', [ 'className' => \App\Model\Table\UsersTable::class, 'table' => 'users', 'entityClass' => 'App\Model\Entity\User', ]); $inactiveUsers = $this->paginate( $inactiveUsersTable->find()->where(['active' => false]), [scope: 'inactive_users'] ); $this->set(compact('users', 'inactiveUsers')); } } // templates/Users/index.php <?php // call `setPaginated` first with the results to be displayed next, so the paginator use the correct scope for the links $this->Paginator->setPaginated($users); ?> <h2><?= __('Active Users') ?>/h2> <table> <thead> <tr> <th><?= $this->Paginator->sort('name', __('Name')) ?></th> <th><?= $this->Paginator->sort('email', __('Email')) ?></th> <th><?= $this->Paginator->sort('active', __('Active')) ?></th> </tr> </thead> <tbody> <?php foreach ($users as $user): ?> <tr> <td><?= h($user->name) ?></td> <td><?= h($user->email) ?></td> <td><?= $user->active ? 'Yes' : 'No' ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?= $this->Paginator->counter() ?> <?= $this->Paginator->prev('« Previous') ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next('Next »') ?> <?php // call `setPaginated` first with the results to be displayed next, so the paginator use the correct scope for the links $this->Paginator->setPaginated($inactiveUsers); ?> <h2><?= __('Inactive Users') ?>/h2> <table> <thead> <tr> <th><?= $this->Paginator->sort('name', __('Name')) ?></th> <th><?= $this->Paginator->sort('email', __('Email')) ?></th> <th><?= $this->Paginator->sort('active', __('Active')) ?></th> </tr> </thead> <tbody> <?php foreach ($inactiveUsers as $inactiveUser): ?> <tr> <td><?= h($inactiveUser->name) ?></td> <td><?= h($inactiveUser->email) ?></td> <td><?= $inactiveUser->active ? 'Yes' : 'No' ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?= $this->Paginator->counter() ?> <?= $this->Paginator->prev('« Previous') ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next('Next »') ?> And with this you have two paginated tables in the same request.

Clean DI in CakePHP 5.3: Say Goodbye to fetchTable()

This article is part of the CakeDC Advent Calendar 2025 (December 23rd, 2025)

Introduction: The Death of the "Hidden" Dependency

For years, accessing data in CakePHP meant "grabbing" it from the global state. Whether using TableRegistry::getTableLocator()->get() or the LocatorAwareTrait’s $this->fetchTable(), your classes reached out to a locator to find what they needed. While convenient, this created hidden dependencies. A class constructor might look empty, despite the class being secretly reliant on multiple database tables. This made unit testing cumbersome, forcing you to stub the global TableLocator just to inject a mock. CakePHP 5.3 changes the game with Inversion of Control. With the framework currently in its Release Candidate (RC) stage and a stable release expected soon, now is the perfect time to explore these architectural improvements. By using the new TableContainer as a delegate for your PSR-11 container, tables can now be automatically injected directly into your constructors. This shift to explicit dependencies makes your code cleaner, fully type-hinted, and ready for modern testing standards. The Old Way (Hidden Dependency): public function execute() { $users = $this->fetchTable('Users'); // Where did this come from? } The 5.3 Way (Explicit Dependency): public function __construct(protected UsersTable $users) {} public function execute() { $this->users->find(); // Explicit and testable. }

Enabling the Delegate

Open src/Application.php and update the services() method by delegating table resolution to the TableContainer. // src/Application.php use Cake\ORM\TableContainer; public function services(ContainerInterface $container): void { // Register the TableContainer as a delegate $container->delegate(new TableContainer()); }

How it works under the hood

When you type-hint a class ending in Table (e.g., UsersTable), the main PSR-11 container doesn't initially know how to instantiate it. Because you've registered a delegate, it passes the request to the TableContainer, which then:
  1. Validates: It verifies the class name and ensures it is a subclass of \Cake\ORM\Table.
  2. Locates: It uses the TableLocator to fetch the correct instance (handling all the usual CakePHP ORM configuration behind the scenes).
  3. Resolves: It returns the fully configured Table object back to the main container to be injected.
Note: The naming convention is strict. The TableContainer specifically looks for the Table suffix. If you have a custom class that extends the base Table class but is named UsersRepository, the delegate will skip it, and the container will fail to resolve the dependency.

Practical Example: Cleaner Services

Now, your domain services no longer need to know about the LocatorAwareTrait. They simply ask for what they need. namespace App\Service; use App\Model\Table\UsersTable; class UserManagerService { // No more TableRegistry::get() or $this->fetchTable() public function __construct( protected UsersTable $users ) {} public function activateUser(int $id): void { $user = $this->users->get($id); // ... logic } } Next, open src/Application.php and update the services() method by delegating table resolution to the TableContainer. // src/Application.php use App\Model\Table\UsersTable; use App\Service\UserManagerService; use Cake\ORM\TableContainer; public function services(ContainerInterface $container): void { // Register the TableContainer as a delegate $container->delegate(new TableContainer()); // Register your service with the table as constructor argument $container ->add(UserManagerService::class) ->addArgument(UsersTable::class); }

Why this is a game changer for Testing

Because the table is injected via the constructor, you can now swap it for a mock effortlessly in your test suite without touching the global state of the application. $mockUsers = $this->createMock(UsersTable::class); $service = new UserManagerService($mockUsers); // Pure injection!

Conclusion: Small Change, Big Impact

At first glance, adding a single line to your Application::services() method might seem like a minor update. However, TableContainer represents a significant shift in how we approach CakePHP architecture. By delegating table resolution to the container, we gain:
  • True Type-Safety: Your IDE and static analysis tools now recognize the exact Table class being used. This is a massive win for PHPStan users—no more "Call to an undefined method" errors or messy @var docblock workarounds just to prove to your CI that a method exists.
  • Zero-Effort Mocking: Testing a service no longer requires manipulating the global TableRegistry state. Simply pass a mock object into the constructor and move on.
  • Standardization: Your CakePHP code now aligns with modern PHP practices found in any PSR-compliant ecosystem, making your application more maintainable and easier for new developers to understand.
If you plan to upgrade to CakePHP 5.3 upon its release, this is one of the easiest wins for your codebase. It’s time to stop fetching your tables and start receiving them. This article is part of the CakeDC Advent Calendar 2025 (December 23rd, 2025)

We Bake with CakePHP