Where should I add data for an associated model in cakephp-3

246 views Asked by At

I would like to create a few default Entities for my users when they register an account, a good example being a Profile, where initially there will be no data from the user registration form, but as all User entities should have a Profile it still seems fitting to create it.

Before you say 'but there is no data, so just cope with this in your controller/views' - yes I know, but not all my use cases would allow for it, and some require that empty/default data.

Is this something that should be added to the data from the register form in my controller, before doing the save? For me it seems more logical that there should be something in my model which says a valid user has a Profile, and if there is no data there to create some (perhaps using a username as the profile Full Name).

  1. Is this something achievable in the beforeSave callback or from a controller?

  2. Is there a minimum I would need to have in a patchEntity for the related entity to save properly (my current attempts have the Profile in debug, but none of the data I thought I was setting, thus nothing saves)

Many thanks

1

There are 1 answers

2
Lukasstr On

I hope i got your questions right.

  1. yes why shouldn't it be possible? Simply create an associated(http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations) entry and make the fields nullable.

  2. To save related you should follow the convention user(id,name,pw,...) profile(id,user_id,...) to make sure a user has only one profile you could make user_id unique.