【问题标题】:How to retrieve serialized data in Form::model and populate array of Form::select with multiselect in laravel如何在 Form::model 中检索序列化数据并在 laravel 中使用多选填充 Form::select 数组
【发布时间】:2015-04-15 01:44:47
【问题描述】:

我的数据库中保存了一个序列化数据,它是一个类别数组中的值。我创建这个是因为它很容易管理选择的类别。

因此,为了创建“页面”,我创建了 create.blade.php 页面和用于多选类别的表单。

{{ Form::open(['role' => 'form', 'method' => 'post', 'route' => 'admin.games.store', 'files' => true]) }}
{{ Form::select('categories[1][]', $platform, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[2][]', $genre, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[3][]', $developer, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::close() }}

我在控制器中定义了 $developer、$genre 和 $platform,这基本上是特定 id 下的类别列表。

$platform = Category::->where('type', '=', 1)->lists('name', 'id');

所以这会返回一个视图的所有类别的数组。

----------------
| name    | id |
----------------
| Windows |  1 |
----------------
| Linux   |  2 |
----------------
| MacOS   |  3 |
----------------

所以这一切都很好,我的选择表单与我指定的类别一起正常工作,提交后我得到一个 array 的值,因为无法保存数组,我序列化很简单:

serialize(Input::get('categories')

而且我的数据库中有序列化数据,我知道如果我需要搜索等,有人会说这不是一个好方法……我将无法使用该字段。但对我来说,我只需要存储所选类别的 id 并同时查询它们。所以这对我有好处。

但是现在我遇到了一个问题,我在编辑页面时找不到获取该数据的方法。

我使用Route::controller,因此您知道页面是如何更新、存储、编辑、创建的工作流程......而且由于表单可以使用Form::model 自动填充字段,我以前使用过它,这是一个非常好的功能。但是当我编辑页面时,我现在不知道如何填充这些字段。

这是我的 edit.blade.php 上的一个表格

{{ Form::model($game, ['role' => 'form', 'method' => 'PUT', 'route' => ['admin.games.update', $game->id ], 'files' => true]) }}
{{ Form::select('categories[1][]', $platform, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[2][]', $genre, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[3][]', $developer, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::close() }}

那么在使用Form::model 编辑页面时,我如何获取该序列化数据并使用选定类别填充选择字段。任何想法,我在网上搜索过,没有答案。

【问题讨论】:

    标签: php arrays forms laravel-4


    【解决方案1】:

    我想这应该告诉你你需要知道什么:Getting selected values from a multiple select form in Laravel

    所以不是传入一个空的第三个参数,而是传入一个选定值的数组。

    【讨论】:

    • 好吧,您不太正确,但我会进一步调查以了解多项选择。当您使用Form::model 而不是Form::open 而不是Form::model 时会自动填充该字段,但我必须将其设置为null,因为我有多个和类的第四个参数。在我之前构建的表单中,我没有使用多个数组进行选择,即使第三个参数为空,它也可以工作,因为 Form::model 填满了它。
    • 啊,我明白你的问题是什么了。我不认为您可以使用 Form::model 执行此操作,除非您为选择对象编写自定义填充器。 Form::model 期望在模型对象中找到数据,而类别数组将不存在(而是一个序列化数组)。在这种情况下,也许在反序列化数组后使用 Form::open 并手动填充表单数据可能更容易。
    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2018-12-02
    • 2022-10-20
    相关资源
    最近更新 更多