My form is not populating when there is some validation error in the input data. Laravel Collective

我与影子孤独终老i 提交于 2021-01-29 03:33:49

问题


Hope yo are all doing great. I am using Laravel 5.3 and a package LaravelCollective for form-model binding. I have subjects array that I want to validate and then store in database if there is no error in the input data.

The following snippets show the partial view of form, other views, rules for validations and controller code.

UserProfile.blade.php

                    <!-- Panel that Adds the Subject - START -->
                    <div class="col-md-12">
                        <div class="panel panel-default" id="add_Subject_panel">
                            <div class="panel-heading">Add Subject(s):</div>
                            <div class="panel-body">
                                {!! Form::open( array('method'=>'post', 'url'=>route('user.store.subject', 1)) ) !!}
                                    @include('user.partials.subjects', ['buttonText'=>'Add Subject(s)'])
                                {!! Form::close() !!}
                            </div>
                        </div>
                    </div>
                    <!-- Panel that Adds the Subject - END -->

subjects.blade.php

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

    <div class="subject-list">
        <div class="input-group subject-input">
            <input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />
            <span class="input-group-btn">
                <span class="btn btn-default">Primary subject</span>
            </span>
        </div>
    </div>

    <div class="text-right">
        <br />
        <button type="button" class="btn btn-success btn-sm btn-add-subject"><span class="glyphicon glyphicon-plus"></span> Add Subject</button>
    </div>

    <div class="form-group">
        <div class="col-md-6 col-md-offset-4 text-right">
            <button type="submit" class="btn btn-primary">
                {{ $buttonText }}&nbsp; <i class="fa fa-btn fa-subject"></i> 
            </button>
        </div>
    </div>


@push('scripts')

{{-- <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> --}}
<script src="{{ asset('scripts/jquery-2.2.4.min.js') }}" type="text/javascript" charset="utf-8" async defer></script>

<script>

        $(function()
        {

            $(document.body).on('click', '.btn-remove-subject', function(){
                $(this).closest('.subject-input').remove();
            });

            $('.btn-add-subject').click(function()
            {
                var index = $('.subject-input').length + 1;

                $('.subject-list').append(''+
                    '<div class="input-group subject-input" style="margin-top:20px; margin-bottom:20px;">'+
                        '<input type="text" name="name['+index+']" class="form-control" value="" placeholder="Subject" />'+
                        '<span class="input-group-btn">'+
                            '<button class="btn btn-danger btn-remove-subject" type="button"><span class="glyphicon glyphicon-remove"></span></button>'+
                        '</span>'+
                    '</div>'
                ); 
            });
        });


</script>

@endpush

I want to validate all the subjects passed as an array to the controller using a custom created form request. the following is the code for that form request

SubjectRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SubjectRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // dd("Rules Area");
        foreach($this->request->get('name') as $key => $val)
        {

            $rules['name.'.$key] = 'required|min:5|max:50';
        }
        // dd($rules);
        return $rules;
    }

    public function messages()
    {
        // dd('Message Area. . .');
        $messages = [];
        foreach($this->request->get('name') as $key => $val)
        {
            $messages['name.'.$key.'.required'] = ' Subject Name '.$key.'" is required.';
            $messages['name.'.$key.'.min'] = ' Subject Name '.$key.'" must be atleast :min characters long.';
            $messages['name.'.$key.'.max'] = ' Subject Name '.$key.'" must be less than :max characters.';
        }
        // dd($messages);
        return $messages;
    }
}

the following is the code for controller method I am using to store inputted array data to database.

    public function storeSubjects(SubjectRequest $request)
    {
        $data = $request->all();

        // save logic
        dd($data);
    }

Problem: My form is not populating when there is some validation error in the input data. After getting validation errors, my input fields are blank.


回答1:


Problem

In subject.blade.php, your code looks like

 <input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />

Your fields are not populating because you have left value attribute blank.

Solution:

Pass the old value to solve your problem.

    <input type="text" name="name[]" class="form-control" value="{{old('name[]')}}" placeholder="Subject" />



回答2:


Use Form Model Binding instead

https://laravelcollective.com/docs/5.3/html#form-model-binding

{{ Form::model($user, [....]) }}
   {{ Form::text('firstname', null, [...]) }}
{{ Form::close() }}


来源:https://stackoverflow.com/questions/39658311/my-form-is-not-populating-when-there-is-some-validation-error-in-the-input-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!