LoginSignup
22
25

More than 5 years have passed since last update.

CakePHP 動的セレクトボックスの作り方

Last updated at Posted at 2014-12-16

ある選択値によって次項のセレクトボックスの中身を変えたいとき。

■CakePHP
・Controller

public function getOptions($id = null) {
    $list = $this->SampleModel->getOptions($id);
    $this->set('optionList', $list);
    $this->layout = false;
}

単にリストを設定しているだけだが、ポイントは「$this->layout = false;」こいつがいないとdefault.ctpを丸ごと返却してしまう。

・View
上記のコントローラのfunctionの対になるもの

<?php foreach ($optionList as $k => $v): ?>
  <option value="<?php echo h($k);?>"><?php echo h($v);?></option>
<?php endforeach; ?>

コントローラ内のセット名「'optionList'」に合わせる。

・Model

public function getOptions($id = null) {
    // デフォルト値
    $result = array("" => "選択してください");

    $query = array(
        'fields' => array('id', 'name'),
        'order' => array('SampleModel.id ASC')
    );
    if (!empty($id)) {
        $query = $query + array('conditions' => array('SampleModel.id' => $id));
    }
    $result = $result + $this->find('list',$query);

    return $result;
}

■jQuery

$('#first-select').bind("change keyup", function() {
    var id = $("#first-select").val();
    $("#change-select").load( "./getOptions/"+id);
});

idがfirst-selectの値が変更されたとき、idがchange-selectであるセレクトボックスにoptionのリストを読み込ませている。

22
25
2

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
22
25