CakePHP 4
I do have this working, but I’m sure its a hacky (non-cake) solution.
The logged in user has the ability to edit his own account, specifically their name, and I use that name which I get via: $this->Authentication->getResult()->getData()->fullname
.
When the user edits their name, on save it goes back to the front screen, where it welcomes them by name. In my UsersController.php I have this: -
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => [],
]);
$this->Authorization->authorize($user);
if ($this->request->is(['patch', 'post', 'put']))
{
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user))
{
if ($user->id === $this->loggedInID) //if edited by owner (not admin)
$this->Authentication->getResult()->getData()->offsetSet('fullname', $user->fullname);
where that last line is how I am putting my fullname field back into my Authentication object.
In my AppController I set a few variables which I use site-wide, thus in my beforeFilter()
$data = $this->Authentication->getResult()->getData(); //actual user entity, null when not logged in
$this->isLoggedIn = $this->Authentication->getResult()->isValid();
$this->loggedInID = $this->isLoggedIn ? $data->id : -1;
$this->loggedInEmail = $this->isLoggedIn ? h($data->email) : "";
$this->loggedInFullname = $this->isLoggedIn ? h($data->fullname) : ""; // h() to sanitise
$this->adminLevel = $this->isLoggedIn ? $data->adminlevel : -1;
$this->set(['isLoggedIn' => $this->isLoggedIn,
'loggedInID' => $this->loggedInID,
'loggedInEmail' => $this->loggedInEmail,
'loggedInFullname' => $this->loggedInFullname,
'adminLevel' => $this->adminLevel
]);
I’m pulling fullname directly from Authentication so I don’t need to load up my user data, as its the only field which can be changed by the user. And I access $loggedInFullname
in my templates.
Question is then, how should I really be doing $this->Authentication->getResult()->getData()->offsetSet('fullname', $user->fullname);
in my UserController edit() context?