0
votes

I'm attempting to insert data from a row in one table into another following a button click. I have a table containing class information. When the user clicks register, I need to take the id of that class and insert it into my timetable table.

So far I'm trying to obtain the id from the POST data. However, when I run the debugger, the id for the class in the array is empty.

My register function:

public function register(){

        $classestimetable = $this->Classestimetable->newEntity();
        if ($this->request->is('post')) {

            $classestimetable->user_id = $this->Auth->user('id');
            $classestimetable->unit_id = $this->request->getData(['id']);
            debug($classestimetable);exit;
            if ($this->Classestimetable->save($classestimetable)) {
                $this->Flash->success(__('The class has been added to your schedule.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The class could not be added. Please, try again.'));
        }

}

Table code:

<tbody>
     <?php foreach ($units as $unit): ?>
         <tr>
                <td hidden><?= h($unit->id) ?></td>
                <td><?= h($unit->className) ?></td>
                <td><?= h($unit->user->firstName), ' ', h($unit->user->lastName) ?></td>
                <td><?= h($unit->classDate) ?></td>
                <td><?= h($unit->classTime) ?></td>
                <td class="actions"> 
                    <?= $this->Form->postLink(__('Register'), ['action' => 'register', $unit->id], ['confirm' => __('Are you sure you want to register for "{0}"?', $unit->className)]) ?>
                </td>
         </tr>
     <?php endforeach; ?>
</tbody>

Debug output:

object(App\Model\Entity\Classestimetable) {

    'user_id' => (int) 11,
    'unit_id' => null,
    '[new]' => true,
    '[accessible]' => [
        'unit_id' => true,
        'user_id' => true,
        'unit' => true,
        'user' => true
    ],
    '[dirty]' => [
        'user_id' => true,
        'unit_id' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[hasErrors]' => false,
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Classestimetable'

}

When working I'm hoping the unit_id field will contain the id of the class the user has chosen to register for.

1

1 Answers

0
votes

You are using $this->request->getData(['id']) to get the id. But in the URL you're building, you haven't named that parameter. Either change to:

['action' => 'register', 'id' => $unit->id]

or else change the definition of your function to:

public function register($id)

and then use $classestimetable->unit_id = $id;