使用php预选择选择选项

问题描述:

我要完成创建post的表单.现在,在创建该帖子之后,如果要编辑它,我将在编辑页面中显示一个select选项,如下所示. (我正在使用Laravel)

I've a form to be completed to create a post. Now after creating that post, if I want to edit it, I'm showing a select option in the edit page something like below. (I am using Laravel)

<select name="posts">
@foreach($posts as $post)

  <option value="{{$post->id}}"> {{$post->name }} </option>

@endforeach
</select>

现在,我需要使用当前的post name预先选择填充的选择字段.我在URL中有一个帖子ID,可以知道我在哪个帖子中.如何选择正确的选项,而不必在options字段中重复相同的选项. ?

Now I need to preselect the populated select field with the current post name. I have a post id in the URL which I can get know in which post I am in. How can I select the right option without making a duplicate of the same in the options field. ?

在循环内部使用if-else结构.

if ( post is equal to the current post ) {
     <option selected="selected" value="{{$post->id}}"> {{$post->name }} </option>
} else {
    <option value="{{$post->id}}"> {{$post->name }} </option>
}

条件取决于您,是否要使用帖子ID或帖子名称进行检查. (无论您拥有什么).

The condition depends on you, whether you want to use the post id or the post name to check. (Whatever you have available).