CakePHP - 创建一个表单来编辑同一模型的多行 [英] CakePHP - Create a form which edits multiple rows of the same model

查看:15
本文介绍了CakePHP - 创建一个表单来编辑同一模型的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个由属于 SubjectGroups 的 Subjects 组成的表单.在视觉上,主题显示在页面上每个主题组的标题下.您将能够编辑学科组或单个学科的名称.

如果我给你一个 HTML 的例子:

<input type="text" value="Subject Group 1"/>

<input type="text" value="主题1"/><input type="text" value="主题2"/><input type="text" value="主题3"/><div class="heading"><input type="text" value="Subject Group 2"/>

<input type="text" value="Subject 4"/><input type="text" value="Subject 5"/><input type="text" value="Subject 6"/>...

  1. 我如何使用 Cake 的 FormHelper 构建表单,以允许我像这样更新多行?

  2. 然后我如何验证和更新 SubjectGroup 和 Subject 模型?

  3. 如何处理每个模型的多个实例(主题 1、主题 2 等)?

解决方案

请参阅 保存相关模型数据 (特别是在Company hasMany Account"示例中使用的数字语法).您应该能够通过循环数据来实现这一点:

$i = $j = 0;foreach($subjectGroups 作为 $subjectGroup):echo $this->Form->input('SubjectGroup.' . $i .'.id');echo $this->Form->input('SubjectGroup.' . $i .'.name');foreach ($subjectGroup['Subject'] 作为 $subject):echo $this->Form->input('Subject.' . $j . '.id');echo $this->Form->input('Subject.' . $j .'.name');$j++;Endforeach;$i++;Endforeach;

至于保存,您只需执行$this->SubjectGroup->saveAll($this->data);.

I am trying to build a form that consists of Subjects, which belong to SubjectGroups. Visually, the subjects are shown on the page under headings of each subject group. You will be able to edit the name of a subject group or an individual subject.

If I were to give you an example of the HTML:

<div class="heading">
    <input type="text" value="Subject Group 1" />
</div>
<input type="text" value="Subject 1" />
<input type="text" value="Subject 2" />
<input type="text" value="Subject 3" />

<div class="heading">
    <input type="text" value="Subject Group 2" />
</div>
<input type="text" value="Subject 4" />
<input type="text" value="Subject 5" />
<input type="text" value="Subject 6" />

...

  1. How do I build the form using Cake's FormHelper that will allow me to update multiple rows like this?

  2. How do I then validate and update both the SubjectGroup and Subject models?

  3. How do I process many instances of each model (subject 1, subject 2, etc.)?

解决方案

See the documentation for Saving Related Model Data (specifically the numeric-syntax used in the "Company hasMany Account" example). You should be able to achieve this by looping over your data:

$i = $j = 0;
foreach ($subjectGroups as $subjectGroup):
    echo $this->Form->input('SubjectGroup.' . $i . '.id');
    echo $this->Form->input('SubjectGroup.' . $i . '.name');
    foreach ($subjectGroup['Subject'] as $subject):
        echo $this->Form->input('Subject.' . $j . '.id');
        echo $this->Form->input('Subject.' . $j . '.name');
        $j++;
    endforeach;
    $i++;
endforeach;

As for saving, you just do $this->SubjectGroup->saveAll($this->data);.

这篇关于CakePHP - 创建一个表单来编辑同一模型的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆