MDB
MDB

Reputation: 360

Retain dynamic row with input when error occurs in validation

I have this table when page load.

<table id="tableServices" class="table table-striped" style="width:100%">
    <thead>
    <th>Name</th>
    <th style="width: 15%; text-align-last: right;"><a href="#" class="fa fa-plus" id="addRow"></a></th>
    </thead>
    <tbody id="list_for_am">
    <tr>
        <td colspan="2">
            <input type="text" placeholder="Enter Name" class="form-control" name="worker[]">
        </td>
    </tr>
    </tbody>
</table>

and add dynamic rows based on the user's preference using this code

$('#addRow').on('click', () => {
    $('#list_for_am').append('<tr>' +
        '<td colspan="2"> ' +
        '<input type="text" placeholder="Enter Name" class="form-control" name="worker[]">' +
        '</td>' +
        '</tr>'
    );
});

and from the controller, to validate if there are null value on one of the array elements I use this

$request->validate([
    'schedule_date' => [
        'required',
        Rule::unique('schedules')->where(function ($query) use($data) {
            $query
                ->where('schedule_date', $data['schedule_date'])
                ->where('schedule_time', $data['schedule_time']);
        })
    ],
    'worker.*' => 'required'
]);

Now, if there are errors, the rows from the table is reset into only one row, not the total number of rows the user added previously. How to retain the number of rows and show the textbox where the error occurs?

Upvotes: 0

Views: 197

Answers (1)

Roman Meyer
Roman Meyer

Reputation: 2872

Try this:

@foreach( old('worker') as $item )
    <td colspan="2">
        <input type="text" placeholder="Enter Name" class="form-control" name="worker[]" value="{{ old('worker')[$loop->index] }}">
    </td>
@endforeach

Upvotes: 1

Related Questions