将 DataTable 数据加载到编辑模式

Load DataTable data to a Edit Modal

我正在尝试为我的数据创建一个编辑功能 table。数据 table 是使用 Yajra Data table 创建的。一切正常,除非当我尝试将现有数据加载到编辑模式时失败。未显示任何错误,但模态未启动。为了便于参考,我在这里只包含了一小部分代码。

模态:

<!-- Update Status Model Box -->
    <div id="updateStatusModal" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content bg-default">                
                <div class="modal-body">
                    <form class="form-horizontal" id="updateStatus">
                        @csrf
                        @method('PUT')
                        <div class="row">
                            <div class="col">
                                <div class="form-group text-center">
                                    <h6 class="font-weight-bold">Stage 1</h6>
                                    <label for="stage_1" class="switch">
                                        <input type="checkbox" class="form-control" id="stage_1">
                                        <div class="slider round"></div>
                                    </label>
                                </div>
                            </div>                            

                        </div>

                        <div class="row">                            

                            <div class="col">

                                <div class="form-group">
                                    <div class="col-md">
                                        <label for="firstname">Coding</label>
                                        <input type="text" class="form-control" id="first_name" value="" placeholder="Enter Completed Page Count">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" name="update_btn" id="update_btn" class="btn btn-outline-warning">Update</button>
                </div>
            </div>
        </div>
    </div>

jquery 函数:

// Edit action
    $(document).on('click', '.updateStatus', function(){


        $tr = $(this).closest('tr');

        var data = $tr.clidren("td").map(function(){
            return $(this).text();
        }).get();

        console.log(data);

        $('#id').val(data[0]);
        $('#job_id').val(data[2]);
        $('#stage_1').val(data[3]);
        $('#conversion').val(data[4]);     

        $('#updateStatusModal').modal('show');

    });

我尝试了我发现的这个方法,但它不起作用。任何人都可以在这里给我任何指示吗?

我只是没有看到你的前端脚本(还有后端代码),但我可以分享你需要的我的实现。它与 this (screenshot) 中展示的一样完美。 在这里,我将放置前后代码。有编辑现有数据表记录的功能,也有删除记录的功能。

前面

<!--HERE ATTACH NECESSARY STYLES-->

<!--VIEW end-->
<link rel="stylesheet" type="text/css" href="{{ asset('css/admin/datatables.min.css') }}"/>
<table id="yajra_datatable" class="table table-bordered">
    <thead>
    <tr>
        <th>Name</th>
        <th>Options</th>
    </tr>
    </thead>
</table>
<div class="modal modal-danger fade" id="modal_delete">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Delete Language</h4>
            </div>
            <div class="modal-body">
                <p>Are You sure You want to delete this Language?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
                <button id="delete_action" type="button" class="btn btn-outline">Submit</button>
            </div>
        </div>
    </div>
</div>
<div class="modal modal-warning fade" id="modal_edit">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Edit Language</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="language_name">Language Name</label>
                    <input name="language_name" id="language_name" type="text" value="" class="form-control" placeholder="Language Name">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
                <button id="edit_action" type="button" class="btn btn-outline">Submit</button>
            </div>
        </div>
    </div>
</div>
<input type="hidden" id="item_id" value="0" />
<!--VIEW end-->

<!--HERE ATTACH NECESSARY SCRIPTS-->

<!--SCRIPTS start-->
<script src="{{ asset('js/admin/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript">
    var YajraDataTable;
    function delete_action(item_id){
        $('#item_id').val(item_id);
    }
    function edit_action(this_el, item_id){
        $('#item_id').val(item_id);
        var tr_el = this_el.closest('tr');
        var row = YajraDataTable.row(tr_el);
        var row_data = row.data();
        $('#language_name').val(row_data.name);
    }
    function initDataTable() {
        YajraDataTable = $('#yajra_datatable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "{{ route('admin.book_languages.ajax') }}",
            "columns":[
                {
                    "data": "name",
                    "name": "name",
                },
                {
                    "data": "",
                    "name": ""
                },
            ],
            "autoWidth": false,
            'columnDefs': [
                {
                    'targets': -1,
                    'defaultContent': '-',
                    'searchable': false,
                    'orderable': false,
                    'width': '10%',
                    'className': 'dt-body-center',
                    'render': function (data, type, full_row, meta){
                        return '<div style="display:block">' +
                            '<button onclick="delete_action(' + full_row.id + ')" type="button" class="delete_action btn btn-danger btn-xs" data-toggle="modal" data-target="#modal_delete" style="margin:3px"><i class="fa fa-remove"></i> Delete</button>' +
                            '<button onclick="edit_action(this, ' + full_row.id + ')" type="button" class="edit_action btn btn-warning btn-xs" data-toggle="modal" data-target="#modal_edit" style="margin:3px"><i class="fa fa-edit"></i> Edit</button>' +
                            '</div>';
                    }

                }
            ],
        });
        return YajraDataTable;
    }
    $(document).ready(function() {
        var YajraDataTable = initDataTable();
        $('#delete_action').on('click', function (e) {
            e.preventDefault();
            $.ajax({
                url: "{{ route('admin.book_languages.delete') }}",
                data: {
                    'item_id': $('#item_id').val(),
                    '_token': "{{ csrf_token() }}"
                },
                type: "POST",
                success: function (data) {
                    $('#modal_delete').modal('hide');
                    YajraDataTable.ajax.reload(null, false);
                    console.log(data.message);
                }
            })
        });
        $('#edit_action').on('click', function (e) {
            e.preventDefault();
            $.ajax({
                url: "{{ route('admin.book_languages.edit') }}",
                data: {
                    'item_id': $('#item_id').val(),
                    'language_name': $('#language_name').val(),
                    '_token': "{{ csrf_token() }}"
                },
                type: "POST",
                success: function (response) {
                    $('#modal_edit').modal('hide');
                    YajraDataTable.ajax.reload(null, false);
                    console.log(data.message);
                }
            })
        });
        $('#modal_delete').on('hidden.bs.modal', function () {
            $('#item_id').val(0);
        });
        $('#modal_edit').on('hidden.bs.modal', function () {
            $('#item_id').val(0);
            $('#language_name').val("");
        });
    });
</script>
<!--SCRIPTS end-->

返回

public function index() {
    return view('admin.book-languages.index');
}
public function ajax() {
    $items = BookLanguage::latest('id');
    return DataTables::of($items)->make(true);
}
public function delete(Request $request) {
    $item_id = $request->get('item_id');
    $item = BookLanguage::find($item_id);
    if(empty($item)) {
        return response()->json([
            'success' => false,
            'message' => 'Item not found!',
        ], 200); // 404
    } else {
        $item->delete();
        return response()->json([
            'success' => true,
            'message' => 'Item successfully deleted.',
        ], 200);
    }
}
public function update(Request $request) {
    $item_id = $request->get('item_id');
    $item = BookLanguage::find($item_id);
    if(empty($item)) {
        return response()->json([
            'success' => false,
            'message' => 'Item not found!',
        ], 404);
    } else {
        $item->name = $request->get('language_name');
        $item->save();
        return response()->json([
            'success' => true,
            'message' => 'Item successfully updated.',
        ], 200);
    }
}

路线

// ...
// book_languages
    Route::group(['prefix' => 'book-languages', 'as' => 'admin.book_languages.',], function () {
        Route::get('all', 'BookLanguageController@index')->name('index');
        Route::get('ajax', 'BookLanguageController@ajax')->name('ajax');
        Route::post('update', 'BookLanguageController@update')->name('edit');
        Route::post('delete', 'BookLanguageController@delete')->name('delete');
    });
// ...

我认为这可以帮助您和其他人构建所需的功能。这里也可以有更多的提示评论,但因为它不小,我可以稍后通过post评论回答。

我正在构建一个 Laravel 类似 ERP 的 Web 应用程序,并且正在实现一个像您一样的 CRUD 功能模式。我在 Laravel 中将我的资源 API 制作成了一个服务器端处理应用程序。好吧,请注意我已经将 @extends(layout.app) 和 @section('stylesheet') 部分删掉以直接进入答案。您应该在自己的应用程序中扩展它们以使一切正常。

View.blade 脚本

        <script>
            $(document).ready(function() {
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

    var table = $('#customertable').DataTable({
                    processing: true,
                    serverSide: true,
                    dom: 'B<"top"frli>tp',
                    ajax: {
                        url: "{{ route('customer.index') }}", //Accessing server for data
                    columns: [
                        {data: 'id'}, //data refers to DB column name
                        {data: 'name'}, 
                        {data: 'chiname'}, 
                        {data: 'type'}, 
                        {data: 'action'}, //this is an addColumn item from Controller
                    ]
                });

        $('#createNewcustomer').click(function () {
                    $('#saveBtn').val("create customer");
                    $('#customerid').val('');
                    $('#customerForm').trigger("reset");
                    $('#modelHeading').html("Create New Customer");
                    $('#customermodal').modal('show');
                });

    //Control the modal behavior when clicking the edit button.
                $('body').on('click', '.editcustomer', function () {
                    var customerid = $(this).data('id');
                    $.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
                        $('#modelHeading').html("Edit Customer");
                        $('#saveBtn').val("edit-user");
                        $('#customermodal').modal('show');
                        $('#customerid').val(data.id);
                        $('#name').val(data.name);
                        $('#chiname').val(data.chiname);
                        $('#type').val(data.type);
                    })
                });

//Create a brand-new record
    $('#createNewcustomer').click(function () {
                    $('#saveBtn').val("create customer");
                    $('#customerid').val('');
                    $('#customerForm').trigger("reset");
                    $('#modelHeading').html("Create New Customer");
                    $('#customermodal').modal('show');
                });

//Update
                $('body').on('click', '.editcustomer', function () {
                    var customerid = $(this).data('id');
                    $.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
                        $('#modelHeading').html("Edit Customer");
                        $('#saveBtn').val("edit-user");
                        $('#customermodal').modal('show');
                        $('#customerid').val(data.id);
                        $('#name').val(data.name);
                        $('#chiname').val(data.chiname);
                        $('#type').val(data.type);
                    })
                });

//Save
    $('#saveBtn').click(function (e) {
                e.preventDefault();
                $(this).html('Sending..');
                $.ajax({
                    data: $('#customerForm').serialize(),
                    url: "{{ route('customer.store') }}",
                    type: "POST",
                    dataType: 'json',
                    success: function (data) {
                        $('#customerForm').trigger("reset");
                        $('#customermodal').modal('hide');
                        table.draw();
                        },
                    error: function (data) {
                        console.log('Error:', data);
                        $('#saveBtn').html('Error');}
                });
            });

//Delete
            $('body').on('click', '.deletecustomer', function () {
                var id = $(this).data("id");
                confirm("Are You sure?");
                $.ajax({
                    type: "DELETE",
                    url: "{{ route('customer.store') }}"+'/'+id,
                    success: function (data) {
                        table.draw();
                    },
                    error: function (data) {
                        console.log('Error:', data);
                    }
                });
            });
</script>

View.blade html-table & 情态部分

@section('content')

    <div class="container">
        <div class="card-header border-left"><h3><strong> Customer overview</strong></h3></div>
<br>

        <div class="row">
            <div class="col-md text-right">
                <button type="button" class="btn btn-success" data-toggle="modal" href="javascript:void(0)" id="createNewcustomer">Create Record</button>
            </div>
        </div>

        {{-- Modal --}}
        <div id="customermodal" class="modal fade" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title" id="modelHeading"></h4>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times</span></button></div>
                    <div class="modal-body">

                        <form id="customerForm" name="customerForm" class="form-horizontal">
                            <input type="hidden" name="customerid" id="customerid">

                            <div class="form-group">
                                <label for="name" class="col-sm-6 control-label">Customer Name</label>
                                <div class="col-sm-12">
                                    <input type="text" class="form-control" id="name" name="name" placeholder="Name" value="" maxlength="50" required="">
                                </div>
                            </div>

                           <div class="form-group">
                                <label class="col-sm-6 control-label">Customer Name</label>
                                <div class="col-sm-12">
                                    <input type="text" class="form-control" id="chiname" name="chiname" placeholder="Customer Name" value="" maxlength="50" required="">
                                </div>
                            </div>

                           <div class="form-group">
                                <label class="col-sm-6 control-label">Contract type</label>
                               <div class="col-sm-12">
                                        <select name="type" id="type" class="form-control">
                                                <option value="" disabled>Type</option>
                                                <option value="Government">Government Contract</option>
                                                <option value="Private">Private Contract</option>
                                        </select>
                               </div></div>

                            <br>
                            <div class="col-sm text-right">
                                <button type="submit" class="btn btn-outline-secondary" id="saveBtn" value="create">Save changes</button>
                            </div>

                        </form>
                    </div>
                </div>
            </div>
        </div>

        {{-- Table --}}
    <br>
        <div class="row">
            <br/>
            <br/>
            <div class="form-group col-md-12 align-content-center">
                <table class="table-fluid center-block" id="customertable">
                    <thead>
                        <tr>
                            <th>id</th>
                            <th>ChiName</th>
                            <th>Name</th>
                            <th>Type</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

@endsection

客户控制器

public function index(Request $request)
    {
                $customers = Customer::all();
            }
                return Datatables::of($customers)
                    ->addColumn('action', function($customer){
                        $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$customer->id.'" data-original-title="Edit" class="edit btn btn-outline-info btn-sm editcustomer">Edit</a>';
                        $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$customer->id.'" data-original-title="Delete" class="btn btn-outline-danger btn-sm deletecustomer">Delete</a>';
                        return $btn;})
                    ->rawColumns(['action'])
                    ->make(true);
        }
        return view('customer.Customer'); //my view blade is named Customer under customer dir. put your blade destination here.
    }

    public function store(Request $request)
    {
        Customer::updateOrCreate(['id' => $request->customerid],
            ['name' => $request->name, 'chiname' => $request->chiname,'type' =>$request->type]);
        return response()->json(['success'=>'Product saved successfully.']);
    }

    public function edit($id)
    {
        $customer = Customer::findorfail($id);
        return response()->json($customer);
    }

    public function destroy($id)
    {
        Customer::findorfail($id)->delete();
        return response()->json(['success'=>'Product deleted successfully.']);
    }

模型(选择 A.)$guarded = [] 或 B.)$fillable = ['fields','fields'] 随心所欲)

   class Customer extends Model
    {
        protected $fillable = ['name','chiname','type'];
    }

web.api(路由设置)

Route::resource('customer', 'CustomerController')->middleware('auth');

迁移/数据库模式结构

class CreateCustomersTable extends Migration
{
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('chiname');
            $table->string('type');
            $table->timestamps();
        });
   }

    public function down()
    {
        Schema::dropIfExists('customers');
    }

我没有在其中加入任何保护措施,例如 gate、auth 等。但基本上这是在 Laravel 框架中使用 dataTable 与 JS,Ajax,Jquery,PHP 合而为一的框架。请注意,此类 CRUD 操作的查询直接链接到数据库服务器。如果您想显示 DataTable 处理的数据,请使用您自己的 jquery 函数来获取并在模式上显示它们。我的回答不是最好的,但希望对你有帮助 >:)

(我无法 post 一张图片在这里给你看,因为我没有足够的声誉哈哈。gg)