代码之家  ›  专栏  ›  技术社区  ›  SegFaultDev

如何创建包含多个实体数据的表单?

  •  0
  • SegFaultDev  · 技术社区  · 7 年前

    我一直在想最好的方法,以单一的形式提交多个实体的数据。

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

    例子

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

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


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

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

    但是动物和人类被存储在不同的数据库表中。所以在控制器的update方法中,我必须使用名称(这将是实体的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
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Ohgodwhy    7 年前

    你可以用 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']
    }
    
    推荐文章