1
2

More than 1 year has passed since last update.

Modalで削除機能の実装の仕方(Laravel)

Posted at

プログラミング初心者です。

やりたいこと

LaravelでModalを使って削除機能を実装する際に、JavaScriptを使ってのデータの受け渡しに苦戦したので記録します。

1 Modalを表示させるための削除ボタン

Blade.php
<a class="btn btn-outline-danger" data-toggle="modal" data-target="#SampleModal" data-title="{{ $sample->title }}" data-url="{{ route('delete.sample',['id' => $sample->id]) }}" > 削除 </a>

  • data-*でModalやJSにデータを渡せます。
  • 今回はdata-titledata-urlの値を渡します。(titleやurlは自分で命名できます)
  • data-targetは必ずModalのidと一緒で、頭に「#」をつけます。  

2 Modal実装

Blade.php
<div class="modal fade" id="SampleModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
    //form-inline:文字の量に合わせてモーダルの大きさが変化する
    <form role="form" class="form-inline" method="post" action="">
    @csrf
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel">削除確認</h4>
                </div>
                <div class="modal-body">
                    <p></p>
                </div>
                <div class="modal-footer">
                    <a class="btn btn-light" data-dismiss="modal">閉じる</a>
                    <button type="submit" class="btn btn-danger">削除</button>
                </div>
            </div>
        </div>
    </form>
</div>
  • 元々はfromタグを使っていなく、削除ボタンのところをaタグ使ってhrefでURLを指定していたのですが、データの送信にはaタグは使えず、formタグを使うためbuttonタグに切り替えました。
  • fromタグのaction属性とmodal-bodyのpタグを空欄にしています。

3 Modalにデータ渡すためのJS実装

Blade.php
//modalにtitleとURLのデータを渡すにはJSが必要
<script>
    window.onload = function() {
        $('#SampleModal').on('shown.bs.modal', function (event) {
            var button = $(event.relatedTarget);//モーダルを呼び出すときに使われたボタンを取得
            var title = button.data('title');//data-titleの値を取得
            var url = button.data('url');//data-urlの値を取得
            var modal = $(this);//モーダルを取得

            //Ajaxの処理はここに
            //modal-bodyのpタグにtextメソッド内を表示
            modal.find('.modal-body p').eq(0).text("本当に"+title+"を削除しますか?");
            //formタグのaction属性にurlのデータ渡す
            modal.find('form').attr('action',url);
        });
    }
</script>
  • 簡単な説明をコメントに記載しています。
  • window.onload = function(){}について、ページや画像などのリソース類を読み込んでから処理を実行したいときに利用するイベントハンドラーと言われるものです。
    私の場合これがないと、うまくデータを渡せませんでした。

  • 記事を参考にしながら実装したので、正直JavaScriptについて詳しくありません。jQueryのメソッドが使われているので調べてみてください。

補足

window.onload = function(){}について
これ、一つのページに複数使用することができません。
複数使用する場合は、window.addEventListener('load', function() {}に変えたところ、うまく実行しました。

参考

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