简体   繁体   English

将 DataTable 数据加载到编辑模式

[英]Load DataTable data to a Edit Modal

I am trying to create an edit function for my data table.我正在尝试为我的数据表创建编辑 function。 The data table is created using Yajra Data tables.数据表是使用 Yajra 数据表创建的。 Everything working fine unless when I try to load existing data into the edit modal it fails.除非我尝试将现有数据加载到编辑模式中,否则一切正常。 No error is showing but the modal does not launch.没有显示错误,但模式没有启动。 I have only included a little portion of my code here for easy reference.为了方便参考,我在这里只包含了一小部分代码。

Modal:模态:

<!-- 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 funtion: 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');

    });

I tried this method I found but this is not working.我尝试了我发现的这种方法,但这不起作用。 Can anyone provide me any pointers here?任何人都可以在这里给我任何指示吗?

I've just didn't seen your front scripts (also back-end codes), but instead I can share my implementation for that you need.我只是没有看到您的前端脚本(还有后端代码),但是我可以根据您的需要分享我的实现。 It works perfectly like showed in this (screenshot) .它的工作原理与此(屏幕截图)中显示的完全一样。 Here I'll put front and back codes.在这里,我将放置前后代码。 There is functionality for editing existsing Datatable record, also record deletion.有编辑现有数据表记录的功能,也有记录删除的功能。

FRONT正面

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

BACK背部

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);
    }
}

ROUTES路线

// ...
// 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');
    });
// ...

I think this can help you and others to build wanted functionality.我认为这可以帮助您和其他人构建想要的功能。 Here this could be also with more hint-comments, but as it not small, I can answer later via post comments.这里也可能有更多的提示评论,但由于它不小,我可以稍后通过发表评论来回答。

i am building a Laravel ERP-like web application and am implementing a CRUD function modal like you.我正在构建一个类似于 Laravel ERP 的 web 应用程序,并且正在像您一样实施一个 CRUD function 模态。 I have made mine a server-side processing application with resource APIs in Laravel.我在 Laravel 中使用资源 API 制作了一个服务器端处理应用程序。 Well, please be reminded that i have cut the @extends(layout.app) & @section('stylesheet') parts to go right into the answer.好吧,请注意,我已将 @extends(layout.app) 和 @section('stylesheet') 部分剪切为 go 到答案中。 You should extend them in your own application to make everything work.您应该在自己的应用程序中扩展它们以使一切正常。

View.blade script 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 & modal part View.blade html-table & modal 部分

@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

CustomerController客户控制器

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.']);
    }

Model (pick either A.) $guarded = [] OR B.) $fillable = ['fields','fields'] as you like) Model(选择 A.) $guarded = [] 或 B.) $fillable = ['fields','fields'] 随意)

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

web.api (route setting) web.api(路线设定)

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

Migration / DB schema structure迁移/数据库架构结构

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');
    }

I have not included any protection in it like gate, auth or so.我没有在其中包含任何保护,例如门,身份验证等。 But basically this is the skeleton of doing CRUD with dataTable in Laravel framework with both JS, Ajax, Jquery, PHP all in one.但基本上这是在 Laravel 框架中使用 dataTable 进行 CRUD 的骨架,其中包含 JS、Ajax、Jquery、Z2FEC39232AC845C2 中的一个。 Kindly be reminded that the queries for such CRUD actions are directly linked to the Database server.请注意,此类 CRUD 操作的查询直接链接到数据库服务器。 If you want to show data processed by the DataTable, use your own jquery function to fetch and show them on the modal.如果要显示由 DataTable 处理的数据,请使用您自己的 jquery function 来获取并在模态上显示它们。 My answer is not the best but i hope it helps you >:)我的回答不是最好的,但我希望它可以帮助你>:)

(I could not post a picture to show you here as i dont have enough reputation lol. gg) (我不能在这里张贴图片给你看,因为我没有足够的声誉哈哈。gg)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM