Andre
Andre

Reputation: 638

Laravel/Blade: pre-selected dropdown option

I am using a foreach loop to generate a drop down list via bensampo's ENUMS library, but I need to be able to preselect one of them as I have an edit view and I need it to load the option that is in my database.

My select in my edit view:

<select name="type" id="type" class="form-control">
    @foreach ($MailMessageTypes as $value =>$label)
        <option value="{{$value}}">{{$label}}</option>
    @endforeach
</select>

My function edit in my MailMessageController:

return view('MailMessage.edit', [
    'MailMessage' => $MailMessage],
    ["MailMessageTypes" => MailMessageType::toSelectArray()
]);

I tried to use the enum library's getValues() and getKeys() in the controller but that generates (duplicates) for me, since the foreach keeps generating all options. I am using the select2 plugin

Added: I'm using the select2 plugin for the list.

Upvotes: 3

Views: 6222

Answers (1)

Jason Roman
Jason Roman

Reputation: 8276

On your Edit page, you are passing the existing mail message as $MailMessage. I am assuming your database has its value as id, so it can be accessed as $MailMessage->id. While you are looping through and displaying each option, you need to check if that option's value equals the id of the message you are editing. If it matches, you set the selected attribute on the <option>:

<select name="type" id="type" class="form-control">
    @foreach ($MailMessageTypes as $value => $label)
        <option value="{{$value}}" {{($MailMessage->id == $value) ? 'selected' : ''}}>
            {{$label}}
        </option>
     @endforeach
</select>

In your HTML your <select> would end up looking something like:

<select name="type" id="type" class="form-control">
    <option value="1">COM01</option>
    <option value="2" selected>COM02</option>
    <option value="3">COM03</option>
    // ... the rest of the options
</select>

Upvotes: 4

Related Questions