How to sort a pages field by date?

I could use some help with setting up the hook. I got it to work basically, except of the formatting of the pages field values. Here’s what I have:

    'page.update:after' => function ($page) {
      if($page->is('projects')) {
        // sort pages in the calendar pages field
        $calPages = $page->calendar()->toPages()->sortBy('title', 'asc');

        $page->update(['testfield' => $calPages]);
      }
    }

The output in my testfield is currently

projects/project-a<br />projects/project-b<br />projects/project-c

Is there some easy built-in Kirby method to put after the sort step to format this to

- projects/project-a
- projects/project-b
- projects/project-c

instead?

This should work:

    'page.update:after' => function ($page) {
      if($page->is('projects')) {
        // sort pages in the calendar pages field
        $calPages = [];
        foreach ($page->calendar()->toPages()->sortBy('title', 'asc') as $p) {
          $calpages[] = $p->id();
        }
        $page->update(['testfield' => yaml::encode($calPages));
      }
    }

Thank you! So the hook works, also when feeding back the result into the calendar field. It also immediately updates the sorting of the pages field, just as I inteded. Here’s the final hook code:

    'page.update:after' => function ($page) {
      if($page->is('projects')) {
        // sort pages in the calendar pages field
        $calPages = [];
        foreach ($page->calendar()->toPages()->sortBy('title', 'asc') as $p) {
          $calPages[] = $p->id();
        }

        $page->update(['calendar' => yaml::encode($calPages)]);
      }
    }

Thank you! For me it works, but I can only see the correct sorting once I reload the page… Is there a way to push the sorted list of pages back to the panel for the correct view?