In this example from the book:
https://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option
class StudentsTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Courses', [
'through' => 'CoursesMemberships',
]);
}
}
class CoursesTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Students', [
'through' => 'CoursesMemberships',
]);
}
}
class CoursesMembershipsTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Students');
$this->belongsTo('Courses');
}
}
I want to enter grade
corresponding to course #8 while adding a new student
. I follow these two examples:
https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations
and
https://book.cakephp.org/3.0/en/views/helpers/form.html#associated-form-inputs
and modify add
method in StudentsController.php
public function add()
{
$student = $this->Students->newEntity();
if ($this->request->is('post')) {
$student = $this->Students->patchEntity($user, $this->request->getData(), [
'associated' => [
'Courses']]);
if ($this->Students->save($student,['associated' => ['Courses._joinData']])) {
$this->Flash->success(__('The student has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The student could not be saved. Please, try again.'));
}
$courses = $this->Students->Courses->find('list', ['limit' => 200]);
$this->set(compact('student', 'courses'));
$this->set('_serialize', ['student']);
}
and Students/add.ctp
to have
echo $this->Form->control('courses._ids', ['options' => $courses]);
echo $this->Form->control('courses.5._joinData.grade');
When I select course #8 in the view and enter corresponding grade, I do not see it in CoursesMemberships
table. It adds the record itself, but grade
is not there.