Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Search Plugin

Asyraf Wahi Anuar Updated 4 min read

This tutorial will demonstrate the basic usage of the search plugin in CakePHP 4. Search has become an essential tool in any web information system.

This tutorial may be outdated

It was last reviewed 4 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

This tutorial will demonstrate the basic usage of the search plugin in CakePHP 4. Search has become an essential tool in any web information system. There are many methods to execute search functions in a web information system. Using a search plugin will save more time and be easier. Let assume that in this tutorial, I have a users table with attributes (id, name, email, role). The search function is required to search based on name, email and role.

Download search plugin using composer:

Terminal
composer.phar require friendsofcake/search

Load search plugin:

Terminal
bin/cake plugin load Search

or manually load at ...\src\Application.php

src/Application.phpPHP
public function bootstrap(): void
{
	$this->addPlugin('Search');

Copy-paste your index page (you also can use search function index) and rename it as search.php at ...\templates\Users\search.php and add the following code to generate the search form before the table:

templates/Users/search.phpPHP
<?php
	echo $this->Form->create(null, ['valueSources' => 'query']);
	echo $this->Form->control('search', ['placeholder' => 'Wildcards: * and ?']);
	echo $this->Form->control('role', ['options' => ['' => '- All -', '1' => 'Administrator', '2' => 'Moderator']]);

	echo $this->Form->button(__('Search'), ['class' => 'btn btn-primary']);
	if (!empty($_isSearch)) {
		echo ' ';
		echo $this->Html->link(__('Reset'), ['action' => 'search', '?' => array_intersect_key($this->request->getQuery(), array_flip(['sort', 'direction']))], ['class' => 'btn btn-default']);
	}

	echo $this->Form->end();
?>

Add EventInterface in Controller

Add the EventInterface as shown below:

src/Controller/UsersController.phpPHP
//other codes
namespace App\Controller;

use Cake\Event\EventInterface; //add this

Create Public Function Initialize

src/Controller/UsersController.phpPHP
public function initialize(): void
{
	parent::initialize();

	$this->loadComponent('Search.Search', [
		'actions' => ['search'],
	]);
}
src/Controller/UsersController.phpPHP
public function search()
{
	//Download all records at once
	$this->paginate['maxLimit'] = 999;

	$users = $this->paginate($this->Users->find('search', ['search' => $this->request->getQuery()]));

	$this->set(compact('users'));
	$this->set('_serialize', ['users']);
}

Create a Search Manager

If you need need to search more fields, add more attributes in the fields array.

src/Model/Table/UsersTable.phpPHP
public function initialize(array $config): void
{
	parent::initialize($config);

	//other codes
	
	$this->addBehavior('Search.Search');

	$this->searchManager()
		->value('role')
		->add('search', 'Search.Like', [ 
			'before' => true,
			'after' => true,
			'fieldMode' => 'OR',
			'comparison' => 'LIKE',
			'wildcardAny' => '*',
			'wildcardOne' => '?',
			'fields' => ['name','email','role'],
		]);
}

If you've need more fields eg: username, just add in your view and add another ->value('username') in the search manager.

Below is the sample of the search form output:

Now you should be able to search your data. That all. Happy coding :)

Did this tutorial help?

202 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

CakePHP 4 Soft Delete

A soft delete marks a record as no longer active or valid without deleting it from the database. Soft deletion is a widely used pattern applied for business applications.

5 min read

CakePHP

CakePHP 4 Audit Trail Using AuditStash Plugin

This plugin adds an "audit trail" to any of your Table classes in your application, allowing the web applications to record the creation, change, or deletion of any table's entities. In theory, it will store the old data before replacing it with the new data or content.

3 min read

CakePHP

CakePHP 4 HTML Minify Plugin

Minify HTML source code for CakePHP 4. Minification enhances site performance and accessibility significantly, which immediately translates into a better user experience.

2 min read