I'm trying to save 3 tables of data from PostController and their relationships are as follow:
Post hasMany Student
Student hasAndBelongsToMany Subject
In posts/
I have a multistep form, in the first step of which I have these inputs to save students:
$this->Form->input('Student.0.name');
$this->Form->input('Student.1.name'); //an additional field that maybe added by the user
In the last step, I count the number of students input by the user in step 1 and then output the inputs for subjects accordingly like this:
$this->Form->input('Subject.0.name'); //Subject(s) for student 1
$this->Form->input('Subject.1.name'); //Subject(s) for student 2
But I don't know how to set the field names in Cakephp to save the subjects for each students in Post
model.
I figured it out:
foreach ($this->session->data['Student'] as $key => $value) {
$val = 'Student.' . $key . '.Subject';
echo $this->Form->input($val);
}
The field names for subject
inputs (submitting from Post
model) should be: Student.0.Subject
. And I output the inputs using foreach loop so it's ready for any number of fields added by the user, and each fields correspond to respective student.