LoginSignup
12
15

More than 5 years have passed since last update.

FriendsOfCake/searchが便利

Last updated at Posted at 2015-08-27

FriendsOfCake/searchが便利

はじめに

cakephp3で検索機能を実装するにあたり
2系の時のお馴染みのCakeDCの search プラグインを使って実装できますが、
FriendsOfCakeの search プラグインを使って実装することもできます。

これが意外とスッキリしてて使いやすかったのでご紹介したいと思います。

※FriendsOfCakeはcakephpの中の人達が作っています。

使い方

FriendsOfCake/searchのREADME.mdを行うことでとりあえず動くが一部変更

Controller

public function index()
{
    $this->loadComponent('Search.Prg');
}

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Search.Prg');
}

に変更する。

actionメソッドの前にしないとfriendsofcakeのPrgComponent.phpのstartupが動かない。

実際に使ってみる

usersテーブルにnameというカラムがあり、テキストのフォームに入力した文字列と一致したものを取得する

model/table

public function initialize(array $config)
{
    $this->addBehavior('Search.Search');
}
public function searchConfiguration()
{
    $search = new Manager($this);
    $search
    ->value('name', [
        'field' => $this->aliasField('name')
    ]);
    return $search;
}

controller

public function index()
{
    $query = $this->Companies
        ->find('search', $this->Users->filterParams($this->request->query))
        ->contain(['Users']);
    $this->set('users', $this->paginate($query));
    $this->set('_serialize', ['users']);
}

view

<?= $this->Form->create('Post'); ?>
<?= $this->Form->input('name', ['type'=>'text']); ?>
<?= $this->Form->button(__('Submit')); ?>
<?= $this->Form->end(); ?>

こんな感じでいけます。

一致じゃなく含むで検索したい場合(like検索)

model/table

public function searchConfiguration()
{
    $search = new Manager($this);
    $search
    ->like('name', [
        'before' => true,
        'after' => true,
        'field' => $this->aliasField('name')
    ]);
    return $search;
}

beforeとafterは前方後方の曖昧検索をする/しないの設定になります。

その他

FriendsOfCake/search/src/Type/Maneger.phpにあるので見てみるといいです。

12
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
15