7

I have a dropdown using wire:model

<div class="form-group">
    <label>Menu</label>
    <select wire:model="chapter_id" class="form-control @error('chapter_id') is-invalid @enderror" placeholder="Menu">
        @foreach ($chapters as $chapter)
            <option value="{{ $chapter->id }}">{{ $chapter->name }}</option>
        @endforeach
    </select>
    @error('chapter_id')
        <div class="invalid-feedback">{{ $message }}</div>
    @enderror
</div>

It works if I do change the option (the $chapter_id assigned successfully). But, if I leave it default (not change the option), or it has only an option, the $chapter_id will not assigned $chapter_id not assigned

Can you guys help me to solve this issue?

Zaky D.
  • 69
  • 1
  • 1
  • 5
  • You have to set a default value to `chapter_id`. I don't think there's another work-around. At least I didn't find any and it make sense to me. – Clément Baconnier May 01 '21 at 08:18

2 Answers2

5

I see 2 ways to work around this. As tell the other before, one have an option for advice the user to select an option

<option value="">Please select</option>

and the other have a defaul value for this property

public $chapter_id = '1';

if this value is required on submit you have to refer it in the rules

protected $rules = [
'chapter_id' => 'required'
];
Prospero
  • 2,190
  • 2
  • 4
  • 18
3

wire:model is only set or updated on change. Hence if you are already on the item (or there is only one), it will not be triggered. You could work around this using wire:init, but I don't see much benefit compared to setting it directly in your mount-method of the component.

My solution is to add an "Please select" entry as the first one. This enforces to trigger a change by selecting the item in question (even if only one option is available).

spekulatius
  • 1,434
  • 14
  • 24