jrdavidson's avatar

Using Old with Multiple Select Dropdown

I"m trying to figure out what I"m doing wrong in my old() function so that if my form fails it will take the selections that were made if there were some and when it reloads the form it will prepopulate the options the user had selected. I also am including the validation rules.

'matches.*.stipulations' => 'array|not_in:0',
<select class="form-control" id="stipulations" name="matches[{{ $x }}][stipulations][]" multiple="multiple">
        <option value="0">Choose One</option>
        @foreach(App\Models\Stipulation::all() as $stipulation)
            <option value="{{ $stipulation->id }}" {{ old('matches.'.$x.'.stipulations[]') == $stipulation->id ? 'selected="selected"' : '' }}>{{ $stipulation->name }}</option>
        @endforeach
</select>
0 likes
7 replies
jrdavidson's avatar

@tisuchi I looked over and tried this solution and for some reason it selects all of the options instead of the couple in testing the form submission.

<select class="form-control" id="stipulations" name="matches[{{ $x }}][stipulations][]" multiple="multiple">
        <option value="0">Choose One</option>
        @foreach(App\Models\Stipulation::all() as $stipulation)
            <option value="{{ $stipulation->id }}" {{ collect(old('matches.'.$x.'.stipulations[]->contains($stipulation->id)')) ? 'selected="selected"' : '' }}>{{ $stipulation->name }}</option>
        @endforeach
    </select>
tisuchi's avatar
tisuchi
Best Answer
Level 70

How about this?

<select class="form-control" id="stipulations" name="matches[{{ $x }}][stipulations][]" multiple="multiple">
        <option value="0">Choose One</option>
        @foreach(App\Models\Stipulation::all() as $stipulation)
            <option value="{{ $stipulation->id }}" @if(old('matches['.$x.'][stipulations][]') == $stipulation->id) {{ 'selected' }} @endif>{{ $stipulation->name }}</option>
        @endforeach
</select>
1 like
jrdavidson's avatar

@tisuchi Unfortunately as good as a suggestion it is, it still gave me the same the same results and actually what your code will do is select all the options even after loading the create page for the first time.

Mahaveer's avatar

@if (old("matches")){{ (in_array($stipulation->id, old("matches")) ? "selected":"") }}@endif

1 like

Please or to participate in this conversation.