Laravel 5-使用数据库值和旧值预填充HTML选择

时间:2018-10-05 13:36:34

标签: laravel laravel-5

我正在尝试在Laravel 5应用中使用“旧”来在这样的编辑路径上预先填充选择表单...

<select id="category" name="category" required>
    <option value="">Select</option>
    <option value="animal" @if (old('category') == "animal") {{ 'selected' }} @endif>Animal</option>
    <option value="vegetable" @if (old('category') == "vegetable") {{ 'selected' }} @endif>Vegetable</option>
    <option value="mineral" @if (old('category') == "mineral") {{ 'selected' }} @endif>Mineral</option>
</select>

这很好用,并在验证失败时保留选定的选项,但是我试图使其起作用,以便在页面首次加载时预先填充。

如何确定这是第一次加载编辑页面,还是在验证失败后重新加载?还是有更好的方法来做到这一点?

2 个答案:

答案 0 :(得分:2)

假设您已将category值发送为$category
因此,在每个<option>标签中,

<option value="animal" 
    {{ old('category') == 'animal' ? ' selected' :
        $category == 'anumal' ? ' selected' : '' }}>
            Animal
</option>

正在发生的事情:

if there is an old value and its matching, select this,
else if the original value is matching select this,
else do nothing.

答案 1 :(得分:1)

old 函数的第二个参数与默认值/初始值一起使用:

<option value="animal" @if (old('category', 'animal') == "animal") {{ 'selected' }} @endif>Animal</option>

如果在闪烁的输入中找不到旧值,则第二个参数将作为函数结果返回。

相关问题