For simplicity sake, I have simplified my tables to get my core need across.
I have two tables: admins and users. The admin table simple holds certain information that is not entirely relevant to the question.
Admins:
+----+---------+
| id | user_id |
+----+---------+
| 1 | 20 |
+----+---------+
| 2 | 25 |
+----+---------+
| 3 | 27 |
+----+---------+
Users:
+----+--------+-----------+
| id | name | surname |
+----+--------+-----------+
| 20 | Name 1 | Surname 1 |
+----+--------+-----------+
| 25 | Name 2 | Surname 2 |
+----+--------+-----------+
| 27 | Name 3 | Surname 3 |
+----+--------+-----------+
The idea is that when a super admin saves a new user, the fill in a form, being a user registration for of sorts and upon saving it saves the user and creates the admin record with the newly created user id.
Obviously the admin record cannot be created without the user account existing as it requires the user id. Cake simple returns an error saying "user_id is required".
This is my form:
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Add Admin') ?></legend>
<?php
echo $this->Form->input('user.name');
echo $this->Form->input('user.surname');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I have tried creating a user with an admin association and the other way around:
$admin = $this->Admins->newEntity();
if($this->request->is('post')) {
$this->Admins->patchEntity($admin, $this->request->data,[
'associated' => ['Users']
]);
$savedAdmin = $this->Admins->save($admin);
}
and
$user = $this->Admins->Users->newEntity();
if($this->request->is('post')) {
$this->Admins->Users->patchEntity($user, $this->request->data,[
'associated' => ['Admins']
]);
$savedUser = $this->Admins->Users->save($user);
}
I do not what to save separate entities because I know it is possible to saved associated data, I'm just not really how to saved the admin record as it relies on the user record.