【问题标题】:How to create a form that contains data for multiple entities?如何创建包含多个实体数据的表单?
【发布时间】:2018-06-14 23:35:57
【问题描述】:

我一直在尝试考虑以一个表单为多个实体提交数据的最佳方式。

我的用例是我有一个包含多行不同实体的表。我希望能够进入“编辑”视图,其中一些列将成为文本字段并允许更改值。

例子

Type   | Name  | Age
Animal | Eevee | 4
Animal | Sandy | 7
Human  | Bob   | 24

[Submit]

在编辑模式下,他们可以更改任何实体的年龄。当用户点击整个列表的保存按钮时,我希望表单提交所有更改。问题是在更新方法中,我需要知道用哪些值更新哪些实体


我正在考虑使用 name 属性将每个实体的实体 id 存储在输入中

<input name="{{$entity->id}} value="{{$entity->age}}"></input>

但动物和人类存储在不同的数据库表中。因此,在控制器的更新方法中,我必须取名称(这将是实体的 id)以及它是否作为人类存在

entityToUpdate = Human::find(id)

如果 entityToUpdate 不存在

entityToUpdate = Animal::find(id)

我们在数据库中使用 UUID,所以这可以工作,但感觉不对。


有没有办法将几个输入组合到一个表单中?

group1
    type=animal
    id = (Sandys ID)
    age = 8
group2
    type=human
    id =(bobs ID)
    age = 25

【问题讨论】:

    标签: laravel forms html-table


    【解决方案1】:

    您可以在输入名称中使用array notation,以便在服务器端获得您想要的:

    @foreach($entities as $entity)
       <input type="hidden" name="group[{{$loop->index}}][type]" value="{{$entity->type}}"/>
       <input type="hidden" name="group[{{$loop->index}}][id] value="{{$entity->id}}"/>
       <input type="text" name="group[{{$loop->index}}][age] value="{{$entity->age}}"/>
    @endforeach
    

    然后在服务器端:

    foreach(request()->get('group') as $entity) {
        // $entity contains ['id'], ['type'], ['age']
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      相关资源
      最近更新 更多