Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - Create a form which edits multiple rows of the same model

Tags:

cakephp

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.)?

like image 408
BadHorsie Avatar asked Sep 12 '11 17:09

BadHorsie


1 Answers

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);.

like image 160
deizel Avatar answered Nov 16 '22 22:11

deizel