TALL Tales

How to Show Existing Value in Dropdown

04 Oct, 2022

I have a select field in my create Post view on this site that lets me add the Category to the Post. The code for that looks like this (I've removed the Tailwind CSS to make it easier to read):

<select id="type">
    <option value="tutorial">Tutorial</option>
    <option value="tip">Tip</option>
    <option value="opinion">Opinion</option>
    <option value="snippet">Snippet</option>
    <option value="error">Error</option>
</select>

Now when I come to Edit the Post I will want the select dropdown to automatically show the existing value from the database. To do that, the code should be:

<select id="type" name="type">
    <option value="tutorial" {{ $post->type === 'tutorial' ? "selected" : "" }}>Tutorial</option>
    <option value="tip" {{ $post->type === 'tip' ? "selected" : "" }}>Tip</option>
    <option value="opinion" {{ $post->type === 'opinion' ? "selected" : "" }}>Opinion</option>
    <option value="snipppet" {{ $post->type === 'snippet' ? "selected" : "" }}>Snippet</option>
    <option value="error" {{ $post->type === 'error' ? "selected" : "" }}>Error</option>
</select>

The relevant code {{ $post->type === 'tutorial' ? "selected" : "" }} uses an inline if statement which is a basic PHP inline if split into three parts.

The first part checks if the type variable from the Post equals the value in the select. The second part returns the value 'selected' if true, the third part returns nothing if not true.

So the resulting HTML will look like:

<select id="type" name="type">
    <option value="tutorial" selected>Tutorial</option>
    <option value="tip">Tip</option>
    <option value="opinion" >Opinion</option>
    <option value="snippet" >Snippet</option>
    <option value="error" >Error</option>
</select>

and your select dropdown will automatically show the existing value from your database.