Get $user on Hook Page Update after

I got a small code for a hook. But I got two problems, I’m not sure if I should use :before or :after and also my code isn’t working when I try to save the user within. Anybody the missing hint?

'hooks' => [
      'page.update:before' => function($page) {
        
        $user = $this->user()->username();
        
        function addToStructure($page, $field, $data = array()){
          $fieldData = page($page)->$field()->yaml();
          $fieldData[] = $data;
          $fieldData = yaml::encode($fieldData);
          try {
            page($page)->update(array($field => $fieldData));
            return true;
          } catch(Exception $e) {
            return $e->getMessage();
          }
        }
        
        addToStructure($page, 'bearbeitungsverlauf',[
          'bearbeitungsverlauf_datum' => date('d.m.Y'),
          'bearbeitungsverlauf_uhrzeit' => date('G:i:s'),
          'bearbeitungsverlauf_autor' => $user
        ]);
        
      }
    ]
1 Like

This should be done with an after hook

Strange one is that with the after.hook it’s working but all other changes I made are not saved

What do you mean?

For example, when I change the text in a field and hit save, the new content isn’t saved … it reverts in the same second to the old value. But the hook is fired and the structure field gets filled.

Hm, does the page save as expected if you remove the hook?

Yes … and also when I change the hook to :before, but then the hook is not working. Seems like they fired to the same time?

No, they don’t fire at the same time. You can use the before hook to modify the results that are saved but you cannot use it to store something in the file system (so you should in any case remove your before hook if it is still there).

Good to know … I’ve tested my code on another installation and it’s working there, really strange! Now I have updated the Kirby core and it’s running well. Maybe there was an error or similar during uploading to the server where creates this bug. Thanks for help :slight_smile:

1 Like