I have a versions table that hasMany version_log. When a version is edited, I’d like to log the change automatically and save the user_id of the person who made the change.
To start, I’ve built a beforeSave method in Model/Table/VersionsTable, but I can’t figure out how to get the ID of the logged in user from the Auth session.
public function beforeSave($event, $entity, $options)
{
if ($entity->isDirty('status')) {
$versionLog = $this->VersionLog->newEmptyEntity();
$versionLog->version_id = $entity->get('id');
$versionLog->old_status = $entity->getOriginal('status');
$versionLog->new_status = $entity->get('status');
$versionLog->user_id = $this->Authentication->getIdentity()->getIdentifier(); // Does not work
$this->VersionLog->save($versionLog);
}
}
Somewhat related… I originally tried to save the associated VersionLog data automatically, by creating an array and then associating it with the parent Version entity, with something like the following
$entity->version_log[] = $versionLog;
But I couldn’t get the associated data to save at all. So I’m probably going about this incorrectly.