我正在尝试构建一个由Subjects组成的表单,这些表单属于SubjectGroups。在视觉上,主题显示在每个主题组的标题下的页面上。您将能够编辑主题组或个别主题的名称。
如果我给你一个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" />
...
如何使用Cake的FormHelper构建表单,这样我可以像这样更新多行?
如何验证和更新SubjectGroup和Subject模型?
如何处理每个模型的许多实例(主题1,主题2等)?
答案 0 :(得分:8)
请参阅Saving Related Model Data 的文档(特别是“Company hasMany Account”示例中使用的数字语法)。您应该能够通过循环数据来实现这一目标:
$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;
至于保存,你只需$this->SubjectGroup->saveAll($this->data);
。
答案 1 :(得分:0)
<div class="heading">
<?php echo $form->input('SubjectGroup.subjectgroup',array('value'=>'subjectgroup 1'));?>
</div>
<?php echo $form->input('Subject.subject',array('value'=>'subject 1'));?>
<?php echo $form->input('Subject.subject',array('value'=>'subject 2'));?>
<?php echo $form->input('Subject.subject',array('value'=>'subject 3'));?>
<div class="heading">
<?php echo $form->input('SubjectGroup.subjectgroup',array('value'=>'subjectgroup 2'));?>
</div>
<?php echo $form->input('Subject.subject',array('value'=>'subject 4'));?>
<?php echo $form->input('Subject.subject',array('value'=>'subject 5'));?>
<?php echo $form->input('Subject.subject',array('value'=>'subject 6'));?>
......
in controller
<?php
$subjctgroup = $this->data['SubjectGroup'];
$subject = $this->data['Subject'];
$this->User->set( $user );
$this->Contractor->set( $subject );
if ($this->Subject->validates() && $this->SubjectGroup->validates())
{
.......//your code for save the data
}
else
{
$this->validateErrors($this->Subject);
$this->validateErrors($this->SubjectGroup);
$this->render();
}
?>