プログラミング奮闘記録

プラグラマーへ奮闘。PHP・Cakephp・JavaScript・isoアプリのコード勉強ブログです。その他の言語やツールなども使用します。

cakephp チェックボックスDBのリストを検索つづき。

昨日のつづきになります。

 

下記のようなコードになりました。

cakephp:2.6.4

searchプラグイン:master

CakeDC/search · GitHub

これ使ってます。

 

前提として、postsとtagsははアソシエーションでhasAndBelongsToManyで繋がっております。

でも、1つの値しか検索できません。

複数のタグが入った記事の検索はしていません。

てか、これ自体hasAndBelongsToManyでアソシエーションする必要性がない。

本来であれば、BelongsToのはず。たぶん。

 

目的なく作っているので。

 

では!!

まずは、viewからいってみます。

>>index.ctp

<?php
echo $this->Form->create('Post', array(
'url' => array_merge(array('action' => 'find'), $this->params['pass'])
));
echo $this->Form->input('tag_id', array('type' => 'select','multiple' => 'checkbox', 'options' => $tag_id));
echo $this->Form->submit('検索');
echo $this->Form->end();
?>

 

こんな感じ。

 

 

 

>>PostsController.php

public $components = array('Search.Prg');

 

//検索条件
public $presetVars = array(
array('field' => 'tag_id', 'type' => 'value'));

 

public function index(){
$this->Post->recursive = 2;
$this->set('posts', $this->paginate());
if($this->request->is('post')){
$this->Post->save($this->request->data);
}


//チェックボックスの項目をデータベースのリストと同じ項目にする
$this->set('tag_id', $this->Post->Tag->find('list',array(
'fields' => array('id', 'Tag'))));


}

 

public function find() {
$this->Prg->commonProcess();
$this->paginate['conditions'] = $this->Post->parseCriteria($this->passedArgs);
$this->set('posts',$this->paginate());
}

 

とりあえずviewのfind.ctpで検索結果を表示させる〜

このfindは、コピペです!

全く公式のドキュメント通りです。

 

検索設定も基本通りです。

presetVarsもコピペです。

 

追加した部分は、indexの中の

$this->set('tag_id', $this->Post->Tag->find('list',array(
'fields' => array('id', 'Tag'))));

くらいです。

viewのindexにtagのリストを渡しています。

'fields' => array('id', 'Tag')を変えていけば簡単にチェックボックスできる。

 

 

ほんでモデル〜

>>Post.php

public $filterArgs = array(
'tag_id' => array(
'type' => 'value'),
);

これもそのまま。

type=valueにしといてね。

 

 

あとは、検索結果を表示させるviewのfindですが、

findはindexと同じで結構です。

 

以上です!!!

あまりあてにしないでください。w

 

できない場合は、公式ドキュメントをみるのが一番早いです!!!!!

見なかったら、私みたいになります。。