</> Code The Pixel

CakePHP 4 Search Plugin

Asyraf Wahi Anuar - May 26, 2020

Estimated reading time: 2 minutes, 19 seconds

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:

composer.phar require friendsofcake/search


Load search plugin:

bin/cake plugin load Search


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

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:

<?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
File Location: ...\src\Controller\UsersController.php
Add the EventInterface as shown below:

//other codes
namespace App\Controller;

use Cake\Event\EventInterface; //add this


Create Public Function Initialize
File Location: ...\src\Controller\UsersController.php

public function initialize(): void
{
	parent::initialize();

	$this->loadComponent('Search.Search', [
		'actions' => ['search'],
	]);
}


Create Public Function Search
File Location: ...\src\Controller\UsersController.php

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
File Location: ...\src\Model\Table\UsersTable.php
If you need need to search more fields, add more attributes in the fields array. 

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:
Tutorial

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


Cite this article (APA 6th Edition)

Popular
CakePHP 4 Print PDF Using CakePDF
May, 17 2020
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 File Upload Using Proffer Plugin
May, 15 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Share
Sharing Link
Click the icon to share