【问题标题】:Laravel show multi-select saved values in edit viewLaravel 在编辑视图中显示多选保存的值
【发布时间】:2017-01-18 23:16:58
【问题描述】:

我有一个 Project 模型,它有一个名为 project_type 的多选字段。我在字段中使用Select2

我在config/enum.php 中设置了一个枚举,如下所示:

<?php

return [
    'project_types' => [
        '0' => 'WordPress Brochure Website',
        '1' => 'WordPress WooCommerce Website',
        '2' => 'Drupal Website',
        '3' => 'SEO',
        '4' => 'Branding',
        '5' => 'Bespoke Web App'
    ]
];

?>

在我的create 视图中,我有一个包含该字段的表单:

{{ Form::open(array('url' => 'projects')) }}

        <div class="form-group">
            {!! Form::label('Project Type') !!}
            {!! Form::select('project_type[]', Config::get('enums.project_types'), null, ['multiple'=>'multiple']); !!}
        </div>

{{ Form::submit('Create Project', array('class' => 'btn btn-primary')) }}

{{ Form::close() }}

然后在我的控制器中,当我保存多选字段值时,我将数组转换为字符串以存储到数据库中:

public function store(ProjectRequest $request)
    {
        $project_type = $request->input('project_type');
        $project_type = implode(',', $project_type);
        $input = $request->except('project_type');
        $input['project_type'] = $project_type;
        Project::create($input);
        return redirect()->route('projects')->with('message', 'Rate created.');
    }

这将以0,1,3 之类的格式存储多选字段。 这可以很好地保存,但是现在当我想编辑项目时,我需要从数据库中提取值并填充多选字段,这就是我正在努力的地方,这就是我在edit 视图中的内容。

   {{ Form::model($project, array('route' => array('projects.update', $project->id), 'method' => 'PUT')) }}

                <div class="form-group">
                    {!! Form::label('Project Type') !!}
                    {!! Form::select('project_type[]', Config::get('enums.project_types'), 1, ['multiple'=>'multiple']); !!}
                </div>

                {{ Form::submit('Update Project', array('class' => 'btn btn-primary')) }}

{{ Form::close() }}

目前您可以看到我已经将多选字段的默认值硬编码为1,但是有没有办法可以将多选字段的默认值设置为存储在数据库中?

【问题讨论】:

  • 对此我不是 100%,但您是否尝试过使用 explode(',', $values) 将数据库中的内容转换回数组,并将结果放在硬编码 1 的位置?
  • 我在你发表评论时就这么做了:) 查看答案

标签: php laravel enums laravel-5.3


【解决方案1】:

基本上正如@Jonathon 在 cmets 中所说的那样,我需要将我的内爆字符串转回一个数组并将其传递给默认值参数:

<?php
    // explode the saved data back into an array                    
    $project_type = explode(',', $project->project_type);
?>

    <div class="form-group">
        {!! Form::label('Project Type') !!}
        {!! Form::select('project_type[]', Config::get('enums.project_types'), $project_type, ['multiple'=>'multiple']); !!}
    </div>

【讨论】:

  • 你可以在'Form::select()'中调用explode函数
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2020-03-28
  • 2020-05-14
  • 2018-09-23
  • 2018-11-01
相关资源
最近更新 更多