laravel 表单选择的默认值(使用 foreach 循环)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34565508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:57:10  来源:igfitidea点击:

Default value on form select (with foreach loop)

formslaravelselectforeachdefault-value

提问by nclsvh

So, I want to achieve a <select>like solution where a default value is equal to the value that is currently in the database, so the 'old value'.

因此,我想实现一个<select>类似的解决方案,其中默认值等于数据库中当前的值,即“旧值”。

1

1

I have this, where I loop a foreach to fill <option>.:

我有这个,在那里我循环一个 foreach 来填充<option>.:

<select id="size"  name="size" class="form-control">
    @foreach ($sizes as $s)
        <option value="{{ $s->value }}">{{ $s->name }}</option>
    @endforeach
</select>
<select id="size"  name="size" class="form-control">
    @foreach ($sizes as $s)
        <option value="{{ $s->value }}">{{ $s->name }}</option>
    @endforeach
</select>

Now where I want to use this is an edit-formin laravel 5.2 where it fills in this form with the current values from the database for the selected user. My input fields with text fill in correctly but this select doesn't.

现在我想使用它的地方是laravel 5.2 中的一个编辑表单,它用所选用户的数据库中的当前值填充这个表单。我的文本输入字段正确填写,但此选择没有。

2

2

Working with Laravel forms I know this is possible to set the default value to S. But I don't know how to loop this is foreach...:

使用 Laravel 表单我知道可以将默认值设置为S。但我不知道如何循环这是 foreach ...:

{{ Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S') }}
{{ Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S') }}

So I need to find a way to set default value with HTML-select tags while in a loop with values from my controller orfind a way to loop in Laravel Forms.. Either is good, as long as it works

所以我需要找到一种方法来设置默认值的 HTML-select 标签,而在循环中使用我的控制器的值,或者找到一种方法在 Laravel Forms 中循环。只要它有效,任何一种都很好

采纳答案by Bogdan Ku?tan

Don't know if this is what You are asking, but if You know current value, You can check it with if statement:

不知道这是否是您要问的,但是如果您知道当前值,则可以使用 if 语句进行检查:

<select id="size"  name="size" class="form-control">
    @foreach ($sizes as $s)
        @if ($s->value == $currentSize)
            <option selected value="{{ $s->value }}">{{ $s->name }}</option>
        @else
            <option value="{{ $s->value }}">{{ $s->name }}</option>
        @endif
    @endforeach
</select>