preselect the select option using php

北战南征 提交于 2019-12-24 13:48:49

问题


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>

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. ?


回答1:


Use an if-else structure inside the loop.

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>
}

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




回答2:


Assuming you pass the current post id into the template as $postId, you could do something like this:

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

    <option value="{{$post->id}}" {{ ($post->id == $postId) ? 'selected="selected"' : '' }}> {{$post->name }} </option>

@endforeach
</select>

Also, since you're using Laravel, a little bit cleaner solution is to use Laravel's Form builder:

{{ Form::select('posts', $posts, $postId) }}


来源:https://stackoverflow.com/questions/27537250/preselect-the-select-option-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!