Search code examples
laravellaravel-livewire

livewire - set default option on a select field


I have a select element like this:

<select wire:model="state" >
    <option value="">Choose a State:</option>
    @foreach($state_list as $abbr=>$state)
        <option >{{$state}}</option>
    @endforeach
</select>

I'd like to have a default state that shows to the user. I've tried setting the $state property directly, and through the mount() method, and by using the SELECT attribute in the option.

As someone pointed out, I didn't have a value field. Additionally, in the actual code, this was a key on a property, so the field was actually name="bank[state]", so I had to add the state property in mount(), like this:

public function mount() {
    $us_state_properties = ['address', 'bank'];
    foreach($us_state_properties as $add) {
        $this->{$add.".state"} = "Florida";
    }
    foreach($this->multi_us_state_properties as $add) {
        $this->{$add.".0.state"} = "Florida";
    }
}

And some fields were dynamically added within the form, as you can see in the second foreach loop.


Solution

  • I think it is because you forget the value in <option value="{{$state}}">{{$state}}</option>

    <select wire:model="state" >
        <option value="">Choose a State:</option>
        @foreach($state_list as $abbr=>$state)
            <option value="{{$state}}">{{$state}}</option> <!-- this -->
            <!-- <option value="{{$abbr}}">{{$state}}</option> --> <!-- or this ? -->
        @endforeach
    </select>
    

    try to force test it

    class FormSelectOption extends Component
    {
        public $state = 'FL';
    
        ...
    }
    

    Reference: https://laravel-livewire.com/screencasts/form-selects