I've got myself confused about the right (or best) way to make sure the associated models are being sent via POST when creating a new User. Both approaches listed bellow are working.
User hasOne UserDetails
Option 1
POST data:
{
"username": "loremipsum",
"password": "123456",
"UserDetails": {
"first_name": "Lorem",
"last_name": "Ipsum"
}
}
PatchEntity UserDetail and add it to User Entity like this:
public function add () {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data(), [
'associated' => [],
'validate' => true
]);
$userDetail = $this->Users->UserDetails->newEntity($this->request->data());
$user->user_detail = $userDetail;
if ($this->Users->save($user, ['associated' =>['UserDetails']]))
{
...
Edit 1: if the UserDetails is not present on the $this->request->data(), the UserDetails entity will get validation errors.
Option 2
POST data:
{
"username": "loremipsum",
"password": "123456",
"user_detail": {
"first_name": "Lorem",
"last_name": "Ipsum"
}
}
Add user_detail validation into UserTable.php:
Edit 2: if I don't add user_detail validation, the request can be sent without the associated model and it will be saved. Adding it makes sure there's a user_detail field on $this->request->data() and the Users entity is the one that will get the validation.
$validator
->requirePresence('user_detail', 'create')
->notEmpty('user_detail');
and patchEntity like this on UsersController.php:
public function add () {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data(), [
'associated' => ['UserDetails'],
'validate' => true
]);
if ($this->Users->save($user, ['associated' =>['UserDetails']]))
{
...
Are these approaches following Cake's conventions or there's a best/clean way to do it?