How to default sort collections JSON in Descending order by creation?

Isn’t there a way to change the default sorting of the JSON entries themselves. I notice when you use the default sort feature when editing a collection it only changes the default sort of the entries as they show in the data preview table - not the JSON itself. Even though custom sort actually changes the JSON.

I’m using this:

The default sort option is only for the entries view in the backend, but you can use an event hook to set the default sort order in your config/bootstrap.php:

$app->on('collections.find.before.CollectionName', function($name, &$options) {

    // skip, if sort is present
    if (!empty($options['sort'])) return;

    // set default sort order to modified 
    $options['sort'] = ['_modified' => -1];

});

I would want to give the cms user the option to change that. Is there an event to make what set there affect the json dynamically without having to manually specify in the code a collection name and sort?

You can reuse the option specified in the collection definitions. Have a look at storage/collections/CollectionName.collection.php.

'sort' => 
  array (
    'column' => '_created',
    'dir' => -1,
  ),

So you could change the code from above to the following (not tested):

$app->on('collections.find.before.CollectionName', function($name, &$options) {

    // skip, if sort is present
    if (!empty($options['sort'])) return;

    $collection = $this->module('collections')->collection($name);

    // also add a fallback in case it is not set (older cockpit version, copy/paste...)
    $column    = $collection['sort']['column'] ?? '_created';
    $direction = $collection['sort']['dir']    ?? -1;

    // set default sort order to modified 
    $options['sort'] = [$column => $direction];

});