0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

laravel-mix datatables

Last updated at Posted at 2021-08-05

datatables + larabel-mix

参考サイト

作成するアプリ

datables+laravel-mixで、
datatablesbootstrap4 , excel , csv(文字化け対策), pdf(文字化け対策), print(印刷) のプロジェクトを作成します♥
◎プロジェクトの作成

###1.プロジェクトの作成

laravel new datatables_laravel-mix_yajra

###2.laravel Mixのための設定

composer require laravel/ui --dev
php artisan ui bootstrap --auth

webpack.mix.jsを編集する

webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .sourceMaps().autoload({
        jquery: ['$', 'window.jQuery']
    });

####mix_urlの設定

config/app.php
 'mix_url' => env('MIX_ASSET_URL', '/datatables_laravel-mix_yajra/public/'),

//上でうまくあたらなかったら。
// 'mix_url' => env('MIX_ASSET_URL', 'http://localhost/datatables_laravel-mix_yajra/public/'),
yarn add jszip
yarn add pdfmake
yarn add datatables.net-bs4
yarn add datatables.net-buttons-bs4

###resources\js\bootstrap.jsにrequireを追記する。

resources\js\bootstrap.js
import pdfMake from "pdfmake/build/pdfmake"; //追記
import pdfFonts from "pdfmake/build/vfs_fonts"; //追記
import jsZip from 'jszip'; //追記

try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    pdfMake.vfs = pdfFonts.pdfMake.vfs; //追記
    window.JSZip = jsZip;               //追記

    require('bootstrap');

    // require( 'jszip' );<-エラーが出るためimportに変更しました。
    // require( 'pdfmake' );<-エラーが出るためimportに変更しました。
    require( 'datatables.net-bs4' ); //追記
    require( 'datatables.net-buttons-bs4' ); //追記
    require( 'datatables.net-buttons/js/buttons.colVis.js' ); //追記
    require( 'datatables.net-buttons/js/buttons.html5.js' ); //追記
    require( 'datatables.net-buttons/js/buttons.print.js' ); //追記
} catch (e) {}

bootstrap4用のcssです。
resources\sass\app.scssに追記してください。

resources\sass\app.scss
@import "~datatables.net-bs4/css/dataTables.bootstrap4.css"; //追加
@import "~datatables.net-buttons-bs4/css/buttons.bootstrap4.css";//追加

@import '~datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css';//responsiveを利用するときは追加

###最後のyarnを実行して完成です。

yarn dev / watch / prod

再度

yarn run dev

###asset関数からmix関数へ変更する
resources\views\layouts\app.blade.phpを編集

resources\views\layouts\app.blade.php
<head>
  <!-- Scripts-->
  <!--コメントアウト <link href="{{ asset('js/app.js') }}"> --> 
  <!-- Styles -->
  <!--コメントアウト <link href="{{ asset('css/app.css') }}" rel="stylesheet"> -->
  <link href="{{ mix('css/app.css') }}" rel="stylesheet">
</head>
<body>
------------
    <!-- コピペした時deferは消去することエラーになる -->
    <script src="{{ mix('js/app.js') }}"></script>
    @stack('js') <!--追記-->
</body>

###Datatablesを記入する。
resources\views\home.blade.phpを編集
とりあえず確認用のブレードです。
ホームブレードに貼り付けてください。
@naga3さんのコードを借用しました。

resources\views\home.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">datatable</div>
                    <div class="card-body">
                        <table id="table">
                            <thead>
                            <tr>
                              <th>No.</th>
                              <th>氏名</th>
                              <th>住所</th>
                              <th>電話番号</th>
                              <th>備考</th>
                            </tr>
                        </thead>
                        <tbody>
                              @for ($no = 1; $no <= 100; $no++)
                              <tr>
                                <td>{{ $no }}</td>
                                <td style="white-space: nowrap">{{ $user->name }}</td>
                                <td>{{ $user->address }}</td>
                                <td>{{ $user->phoneNumber }}</td>
                                <td>{{ $user->realText(25) }}</td>
                            </tr>
                            @endfor
                        </tbody>

                          </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('js')
    <script>
        $(function() {
            $('#table').DataTable({
            dom : 'Bftip',
    buttons: [
        'copyHtml5',
        'excelHtml5',
        'csvHtml5',
        'pdfHtml5',
        'colvis',
    ],
            });
        });
    </script>
@endpush

###最後にルートの登録

routes\web.php
Route::get('/', function () {
    $user = Faker\Factory::create('ja_JP');
    return view('home',compact('user'));
});

datatablesの機能とbootstrap4でスタイルがあたっているかcopyやexcelやcsvやpdf,printがとりあえず機能することを確認する。また、colvisが機能することとheaderにsort印(↑↓)←こんなマークがあるのも確認してください。

localhost/home

datatableスタイル

dom: 'Bftip',<左からボタン、サーチボックス、テーブル、インフォメーション、ページネーションの意味。
この順番で上から下に配置される。
デフォルトはlfrtipこれで、
lはlengthで5件10件とかのボックスやね
fはフィルターやな検索ボックス
rはproccingのらしい、これは見えない
tはテーブルやな
iは何件中の何件みないなやつや
pはページネーション
デフォルトはこの順番で上から下に並ぶ。

公式サイトの説明はここ
さらに、divやクラス名やidをつけたdivで囲むことも可能。
例 公式サイトから。

dom: '<"wrapper"flipt>' の場合

    <div class="wrapper">
      {filter}
      {length}
      {information}
      {pagination}
      {table}
    </div>

dom: '<lf<t>ip>' の場合
<t>でテーブルをdivで囲み
さらに< lf<t>ip >で全体をdivで囲ってる

    <div>
      {length}
      {filter}
      <div>
        {table}
      </div>
      {information}
      {pagination}
    </div>

< t > ---<div>{table}</div>

<div>{table}</div>

<"table .table-border" t > --- <div class="table table-border">{table}<div>

<div class="table table-border">{table}<div>

<"#search" f> ---<div id="search">{filter}<div>

<div id="search">{filter}<div>

<"#search.name" f > ---<div id="search" class="name">{filter}</div>

<div id="search" class="name">{filter}</div>

これを参考にホームブレードのスタイルを変更してみる。

  // dom: 'Bftip',を下に修正
  dom: '<"mb-3 d-flex justify-content-end" B><"d-flex justify-content-between" lpf><"text-nowrap" t>i',

サイトで確認する

localhost.home

自由なクラスとidをつけてスタイリングは自由自在。

dom:'B<"#custom_div">ftip'---空のdiv#id="custom_div"も挿入できる。

      {Button}
  <div id="custom_div"></div> 
      {filter}
      {table}
      {information}
      {pagination}

また、Handlebarsと併用するとYajraの公式サイトの下のリンク先のデモアプリも簡単に作成できます。jabascriptでの記述はフォーマット化されており、記述する必要はありません。htmlとcssと簡単なサーバーサイドの記述で出来上がります。
公式サイトのデモアプリで動作を確認してください。

https://datatables.yajrabox.com/eloquent/master
上のデモアプリは私が作成したコードがありますので、作成手順をコピペして確認できるようにします。

日本語対応に変更する。

###1,datatablesの表記を日本語に変更する。

language: { url:"https://cdn.datatables.net/plug-ins/1.10.15/i18n/Japanese.json",},

###2,csvファイルの文字化けを修正する。

    buttons: [
        'copyHtml5',
        'excelHtml5',
        // 'csvHtml5',これを下に修正
        {
            bom: true, // エクセルで文字化けしないようにbom付き
            extend: 'csvHtml5',
        },
        'pdfHtml5',
    ],

###3,pdfファイルの文字化けを修正する
これが若干めんどくさいです。
手順はこのサイトを参考にしました

https://saka24.blue/index.php/2017/06/30/datatables_pdf/
以下、アナログ手順です。
①public\js\に空のファイルを作成します。
名前はvfs_fonts.jsです。
②つぎに**このサイト**からvfs_fonts.jsのコードをコピーして先程作成したファイルに貼り付けてやります。

public\js\vfs_fonts.js
//ここに貼り付ける。

③resources\views\layouts\app.blade.phpに追記

resources\views\layouts\app.blade.php
   <script src="{{ mix('js/app.js') }}"></script>
    <script src="js/vfs_fonts.js"></script> //リンクはここに貼り付ける
     @stack('scripts')
</body>

④datatablesのコードを修正とobjectを追加する。

resources\views\home.blade.php
@push('js')
    <script>
        $(function() {
            // pdfの文字化け対策のオブジェクトを追記
            pdfMake.fonts = {
                GenShin: {
                    normal: 'GenShinGothic-Normal-Sub.ttf',
                    bold: 'GenShinGothic-Normal-Sub.ttf',
                    italics: 'GenShinGothic-Normal-Sub.ttf',
                    bolditalics: 'GenShinGothic-Normal-Sub.ttf'
                }
            }
            $('#table').DataTable({
                language: {
                    url: "https://cdn.datatables.net/plug-ins/1.10.15/i18n/Japanese.json",
                },
                dom: '<"mb-3 d-flex justify-content-end" B><"d-flex justify-content-between" lpf><"text-nowrap" t>i',
                buttons: [
                    'copyHtml5',
                    'excelHtml5',
                    {
                        bom: true,
                        extend: 'csvHtml5',
                    },
                    {
                        extend: 'pdfHtml5',
                        customize: function(doc) {
                            doc.defaultStyle.font = 'GenShin';
                         
                        },
                    },
                    'colvis',
                ],
            });
        });
    </script>
@endpush

以上日本語の設定は終了。
横幅のカスタマイズもこんな感じで結構自由に設定できる。

{
    extend: 'pdfHtml5',
    customize: function(doc) {
        doc.defaultStyle.font = 'GenShin';
        //横幅を変更する。
        var colWidth = ['auto', 80, '*', '*', '*'];
        doc.content[1].table.widths = colWidth;
    },
},

ダウンロードしたファイルが文字化けしていないのを確認してください。

localhost.home

0
2
1

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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?