通过json/ajax-laravel通过验证导入excel形成

发布于 2025-02-09 09:51:58 字数 3615 浏览 2 评论 0原文

我尝试使用MaatWeb的Laravel Import Excel。我想使用我的表格中的JavaScript“处理错误”。这是我的代码。

雇员

public function collection(Collection $rows)
    {
        Validator::make($rows->toArray(), [
            '*.nik' => 'required',
            '*.name' => 'required',
            '*.id_department' => 'required',
            '*.id_position' => 'required',
            '*.id_group' => 'required',
            '*.id_meet_point' => 'required',
        ])->validate();

        foreach ($rows as $row) {
            Employee::create([
            'nik'           => $row['nik'],
            'name'          => $row['name'],
            'id_department' => $row['id_department'],
            'id_position'   => $row['id_position'],
            'id_group'      => $row['id_group'],
            'id_meet_point' => $row['id_meet_point'],
            ]);
        }        
    }

lospereeecontroller

public function import_excel(Request $request)
    {
        if($request->ajax()){   
            try {
                $file = $request->file('file');
                $nama_file = rand().$file->getClientOriginalName();
                $file->move('file_employee', $nama_file);

                Excel::import(new EmployeeImport, public_path('/file_employee/'.$nama_file));        
                return response()->json([
                    'status'    => 200,
                    'message'   => 'Berhasil di Import'
                ]);
            } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
                $failures = $e->failures();
                foreach($failures as $failure)
                {
                    return response()->json([
                        'status'    => 422,
                        'errors'    => $failure->errors(),
                    ]);
                }
            }  
        }
    }

v_employee.blade

$("#importpost").on("submit", function(e) {
        e.preventDefault();
        var extension = $('#file_upload').val().split('.').pop().toLowerCase();
        if ($.inArray(extension, ['csv', 'xls', 'xlsx']) == -1) {
            alert('Please choose file csv/xls/xlsx!');
        } else {
            var file_data = $('#file_upload').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                url: "{{route('employee.import')}}",
                data: form_data,
                type: 'POST',
                contentType: false,
                cache: false,
                processData: false,
                success: function(response) {
                    /* if (response.status == 442) {
                        $('#importform_errList').show();
                        $('#importform_errList').html('');
                        $('#importform_errList').addClass('alert alert-danger');
                        $('#importform_errList').append('<li>' + response.message + '</li>');
                    } */
                    console.log(response.status);
                    /* $('#importExcel').modal('hide');
                    tampil_table(); */
                }
            });
        }
    });

我已经尝试了此代码,但仍未显示我的表格以验证。错误日志仍然 422(无法处理的内容)。有帮助我吗?我的代码怎么了?

I try Laravel import excel using Maatweb. I want to 'handling error' using Javascript in my form. This is my code.

EmployeeImport

public function collection(Collection $rows)
    {
        Validator::make($rows->toArray(), [
            '*.nik' => 'required',
            '*.name' => 'required',
            '*.id_department' => 'required',
            '*.id_position' => 'required',
            '*.id_group' => 'required',
            '*.id_meet_point' => 'required',
        ])->validate();

        foreach ($rows as $row) {
            Employee::create([
            'nik'           => $row['nik'],
            'name'          => $row['name'],
            'id_department' => $row['id_department'],
            'id_position'   => $row['id_position'],
            'id_group'      => $row['id_group'],
            'id_meet_point' => $row['id_meet_point'],
            ]);
        }        
    }

EmployeeController

public function import_excel(Request $request)
    {
        if($request->ajax()){   
            try {
                $file = $request->file('file');
                $nama_file = rand().$file->getClientOriginalName();
                $file->move('file_employee', $nama_file);

                Excel::import(new EmployeeImport, public_path('/file_employee/'.$nama_file));        
                return response()->json([
                    'status'    => 200,
                    'message'   => 'Berhasil di Import'
                ]);
            } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
                $failures = $e->failures();
                foreach($failures as $failure)
                {
                    return response()->json([
                        'status'    => 422,
                        'errors'    => $failure->errors(),
                    ]);
                }
            }  
        }
    }

v_employee.blade

$("#importpost").on("submit", function(e) {
        e.preventDefault();
        var extension = $('#file_upload').val().split('.').pop().toLowerCase();
        if ($.inArray(extension, ['csv', 'xls', 'xlsx']) == -1) {
            alert('Please choose file csv/xls/xlsx!');
        } else {
            var file_data = $('#file_upload').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                url: "{{route('employee.import')}}",
                data: form_data,
                type: 'POST',
                contentType: false,
                cache: false,
                processData: false,
                success: function(response) {
                    /* if (response.status == 442) {
                        $('#importform_errList').show();
                        $('#importform_errList').html('');
                        $('#importform_errList').addClass('alert alert-danger');
                        $('#importform_errList').append('<li>' + response.message + '</li>');
                    } */
                    console.log(response.status);
                    /* $('#importExcel').modal('hide');
                    tampil_table(); */
                }
            });
        }
    });

I have tried this code but still not show on my form for the validation. The error log still 422 (Unprocessable Content). Any help me ? What's wrong with my code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心意如水 2025-02-16 09:51:58

我找到了其他形式显示验证错误的方法。
所以我像这样更改了代码。

$.ajax({
                url: "{{route('employee.import')}}",
                data: form_data,
                type: 'POST',
                contentType: false,
                cache: false,
                processData: false,
                success: function(response) {
                    if (response.status == 200) {
                        Swal.fire({
                            icon: 'info',
                            title: 'Success',
                            text: 'Import File Berhasil',
                            showCancelButton: false,
                            showConfirmButton: true,
                            confirmButtonColor: '#fb3'
                        });
                        $('#importExcel').modal('hide');
                        tampil_table();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Failed',
                            text: 'Import Gagal. Silahkan cek table excel!',
                            confirmButtonColor: '#fb3',
                            showCancelButton: false,
                            showConfirmButton: true
                        });
                    }
                },
                error: function(data){
                    //console.log(data);
                    Swal.fire({
                            icon: 'error',
                            title: 'Failed',
                            text: 'Import Gagal. Silahkan cek table excel!',
                            confirmButtonColor: '#fb3',
                            showCancelButton: false,
                            showConfirmButton: true
                    });
                }
            });

我添加错误:function(),因为验证在此功能中定义。我只是用自定义单词添加错误消息。因为我不知道如何显示验证的错误(消息)此功能。我只是分享文档。

I find other ways to showing validation error in my form.
So I changed my code like this.

$.ajax({
                url: "{{route('employee.import')}}",
                data: form_data,
                type: 'POST',
                contentType: false,
                cache: false,
                processData: false,
                success: function(response) {
                    if (response.status == 200) {
                        Swal.fire({
                            icon: 'info',
                            title: 'Success',
                            text: 'Import File Berhasil',
                            showCancelButton: false,
                            showConfirmButton: true,
                            confirmButtonColor: '#fb3'
                        });
                        $('#importExcel').modal('hide');
                        tampil_table();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Failed',
                            text: 'Import Gagal. Silahkan cek table excel!',
                            confirmButtonColor: '#fb3',
                            showCancelButton: false,
                            showConfirmButton: true
                        });
                    }
                },
                error: function(data){
                    //console.log(data);
                    Swal.fire({
                            icon: 'error',
                            title: 'Failed',
                            text: 'Import Gagal. Silahkan cek table excel!',
                            confirmButtonColor: '#fb3',
                            showCancelButton: false,
                            showConfirmButton: true
                    });
                }
            });

I add error: function(), because validation define in this function. I just add error message with my custom word. Becase I don't know how showing up error(message) of the validation this function. I just share documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文