ほげほげ

プログラミング、英会話、ヨガ、料理などの備忘録など。

PHP でdatatables を mongodbと使う

HTML側にはCharismaというbootstrapベースの管理画面用のテンプレートを使用しているので、
環境によっては動かないかもです。

出来上がるもの

f:id:sekitaka_1214:20140215132932p:plain

PHP 側のコード

    public function getForDatatables(){
        $collectionName = $_REQUEST['dt_table'] ; // コレクション名をリクエストから取得
        $mongoClient = new \MongoClient() ;
        $collection = $mongoClient->selectCollection("ulna",$collectionName) ;

        // 検索条件なし
        $cursor = $collection->find() ;

        // ページネーション設定
        $cursor->limit($_REQUEST['iDisplayLength']) ;
        $cursor->skip($_REQUEST['iDisplayStart']) ;

        // ソート設定
        $sortType = $_REQUEST['sSortDir_0'] == 'asc' ? 1 : -1 ;
        $sortColIndex = $_REQUEST['iSortCol_0'] ;
        $sortCol = $_REQUEST["mDataProp_${sortColIndex}"] ;
        $cursor->sort(array($sortCol => $sortType )) ;

        $recs = array() ;
        foreach ($cursor as $doc) {
            $doc['_id'] = $doc['_id']->{'$id'} ; // MongoIdのインスタンスを文字列にする
            $recs[] = $doc ;
        }


        // datatables用の結果に変換
        $res = array(
            "aaData" => $recs,
            "sEcho" => $_REQUEST['sEcho'],
            "iTotalRecords" => $cursor->count(),
            "iTotalDisplayRecords" => $cursor->count(), // [注意]表示レコードと思いきや、全レコード
        );

        print(json_encode($res)) ;
        exit ;
    }

HTML側のコード

            <!-- classにdatatablesを指定したら動かなかった -->
            <table class="table table-bordered table-striped bootstrap-datatable" id="table_books">
              <thead>
              <tr role="row">
                <th>_id</th>
                <th>num</th>
                <th>action</th>
              </tr>
              </thead>
              <tbody>
              </tbody>
            </table>

HTML側のjavascriptのコード

$(function(){
  $('#table_books').dataTable({
    sAjaxSource:'/data_tables/get.ufp',
    bServerSide:true,
    bProcessing:true,
    bRetrieve:true,
    "bPaginate": true, // ページング
    "sPaginationType": "bootstrap", // full_numbers

    "aoColumns": [
      { "mDataProp": "_id"},
      { "mDataProp": "num"},
      { "mDataProp": null}
    ],
    "fnServerParams": function ( aoData ) { // サーバー追加送信
      aoData.push( { "name": "dt_table", "value": "hoge" } ); // ここでコレクション名を指定できるように作っています
    },
    oLanguage:{ // 言語設定など
      sLengthMenu:"読み込み件数 _MENU_ 件",
      oPaginate:{ // ページネーション関連
        sFirst:'先頭',
        sLast:'末尾',
        sNext:'次へ',
        sPrevious:'前へ'
      },
      oAria:{
        sSortAscending:'昇順',
        sSortDescending:'降順'
      },
      sEmptyTable:'有効なデータがありません。',
      sZeroRecords:'データがありません。',
      sInfo: '_TOTAL_件中 _START_件目 から _END_件目までのデータを表示しています。',
      sInfoEmpty: '表示するデータが見つかりません。',
      sLoadingRecords: 'データ読み込み中...',
      sProcessing:'データ読み込み中...',
      sSearch: '検索'
    }
  }) ;



}) ;