【问题标题】:How to selected option enum config in laravel/?如何在 laravel/ 中选择选项枚举配置?
【发布时间】:2021-10-10 21:18:57
【问题描述】:

我在 Laravel 刀片中的构建选择存在问题,并且仅使用数据库中的两种类型值。

我的迁移中有专栏:

 $table->enum('options',['contact','about', 'celebrities', 'introduction']);

我必须以刀片形式使用它来更新。

<select name="options" id="options" class="form-control">
    @foreach(config('enum.options') as $key => $value)
        <option value="{{ $key }}" {{ old('options') == $key || $content->options ? 'selected' : '' }} >{{ $value }}</option>
    @endforeach
</select>

【问题讨论】:

  • 我不明白这个问题。你有一个config/enum.php 的文件,它有options 键和相关数据吗?或者您想访问迁移中的可用选项?
  • 是的,我有config/enum.php,它有带有相关数据的options 键。我在内容的编辑页面上,它有一个选择选项 options 。我想在默认情况下在选择选项中查看保存的值。

标签: php laravel


【解决方案1】:

正如您在 comment 中所述,您有一个 config/enum.php 文件。

我认为是这样的;

<?php

return [
    'options' => [
        'contact' => "Contact option name",
        'about'  => "About option name",
        'celebrities' => "Celebrities option name",
        'introduction => "introduction option name",
    ]
];

你有一个刀片文件来显示编辑表单,比如说edit.blade.php

<select name="options" id="options" class="form-control">
    @foreach(config('enum.options') as $key => $value)
    <option value="{{ $key }}" 
        @if($content->options == $key || old('options') == $key) selected @endif
        >
        {{ $value }}
    </option>
    @endforeach
</select>

请记住;如果用户填写了表格并更改了options 选择值;然后被错误重定向回来(出于某种原因)会有一个old('options') 值。在这种情况下,如果$content-&gt;optionsold('options') 不同,则&lt;option ...&gt; 都将包含selected。浏览器将显示带有selected 的最后一项作为当前值。这不是一个完美的解决方案。

也许你可以试试这样的:

@php
    $currentFormOptions = old('options') ? old('options') : $content->options;
@endphp

<select name="options" id="options" class="form-control">
    @foreach(config('enum.options') as $key => $value)
    <option value="{{ $key }}" 
        @if($currentFormOptions == $key) selected @endif
        >
        {{ $value }}
    </option>
    @endforeach
</select>

【讨论】:

    【解决方案2】:

    Laravel 没有内置的方法来检索枚举选项。 根据您的设置,我建议将其放入模型中的数组中:

    class YourModel extends Model {
        public yourEnumOptions = ['contact','about', 'celebrities', 'introduction'];
    ...
    

    对于更动态的解决方案(缺点是额外的数据库查询),您可以在模型中添加一个方法:

    class YourModel extends Model {
        public function getEnumOptions() {
            $options = DB::selectRaw("show columns from yourTable where field = yourField");
            // Transform the query results string into an array here. 
        }
    ...
    

    【讨论】:

    • 它不起作用,我想在点击编辑时选择默认选项
    猜你喜欢
    • 2018-12-14
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2021-12-26
    相关资源
    最近更新 更多