4
4

More than 5 years have passed since last update.

jsTreeの使い方②

Posted at

昨日書き忘れましたが、このプログラムはgithubに全て上げてあります。
jsTreeの元ファイルと見比べると何を変更してあるかが見えるかと思いますので、参考までに。
richui/jstreeが今回の対応分です。

さて本題。

fs.phpの設定

jstreeでデータを表示する場合、id/id/idなどの形でツリーを書かなくてはなりません。
今回は 親カテゴリID/小カテゴリID/孫カテゴリID のかたちで取得します。とはいえこれはpath()でやってくれてるのでほとんど書き換える必要がありません。
is_dirやis_fileは使いませんので、必要のない操作だけをガシガシ削ります。

ツリー表示のためのデータの取得はlst()がメインになります。

lst()

    public function lst($id, $with_root = false) {
        // $dir = $this->path($id);
        $lst = DB::select ()->from ( 'categories' )->where ( 'parent', $id )->execute ()->as_array ();
        $res = array ();
        foreach ( $lst as $item ) {
            if ($item['grade'] == 0 || $item['grade'] == 1) {
                $res [] = array (
                        'text' => $item['name'],
                        'children' => true,
                        'id' => $item['id'],
                        'icon' => 'folder'
                );
            } else {
                $res [] = array (
                        'text' => $item['name'],
                        'children' => false,
                        'id' => $item['id'],
                        'type' => 'file',
                        'icon' => 'file file-txt'
                );
            }
        }
        return $res;
    }

カテゴリを三層までに絞りたかったので、親カテゴリと子カテゴリはフォルダ扱い、孫カテゴリをファイル扱いにしました。
children=>boolで「子要素を作成できるかどうか」が設定されるようなので、ここをそれぞれtrueとfalseに分けてます。
idにはDBから取得してきたカテゴリIDを。

このカテゴリIDが今度はツリー要素がクリックされた時にデータ取得に利用されます。textには表示文字列が入ります。

データ取得はdata()で行います。

data()

    public function data($id) {
        $dirs = DB::select()->from('categories')->where('id',$id)->execute()->as_array();
        $dir=$dirs[0];
        if ($dir['grade'] <=1) {
            // 小カテゴリでなければ下位項目を追加できる
            return array (
                    'type' => 'folder',
                    'content' => json_encode($dir)
            );
        } else {
            // 小カテゴリは下位項目の追加ができない
            return array (
                    'type' => 'txt',
                    'content' => json_encode($dir)
            );
        }
        return $dat;
        throw new Exception ( 'Not a valid selection: ' . $dir );
    }

ソースが汚いのはご愛嬌。
ifの条件分くらいlst()側と合わせればいいのに。

そのほか

create/renameはmkdirとfile_put_contentsをinsertとかupdateに書き換え、deleteはdelete書き込み、あとは正規表現で弾いたりしてるところを適宜書き換え。
この辺複雑な作業はないです以上!

githubのコードでわからないところがあればwikiとかは潰してあるのでここか前の記事まで。
変数名の語彙がほしい。

4
4
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
4
4