Sort (or group) by parent page?


#1

Hi,

I’m refactoring my code and trying to achieve this the sorting of a collection by parent page.

Before, I had 4 collections created : project_featured, side_featured, project and side. All this was aggregated in a collection, and displayed in this order.

Now that I return in my old code, I try to use the sortBy function as it seems more logical and less verbose. So I just aggregated projects and side together, and did a sortBy('featured', 'desc', 'sort', 'asc') on it.

It works, except that projects from regular projects and side projects are now mixed (but sorting by featured or not is ok).

Is there a way to add a parameter in sorting to keep the parent page and achieve what I had before or have I to keep 4 collections and group it afterhand?

Also: what is the difference between sortBy() and groupBy() ?

thanks.


#2

What is that 'sort`field you are sorting by? If you want to sort first by feature and then by parent, your code should probably rather look like this (example):

<?php
$collection = pages([page('blog')->children(), page('projects')->children()])->sortBy('featured', 'desc', 'parent', 'asc');
dump($collection);
?>

Or by intended template:

<?php
$collection = pages([page('blog')->children(), page('projects')->children()])->sortBy('featured', 'desc', 'intendedTemplate', 'asc');
dump($collection);
?>

sortBy() just sorts a collection, while groupBy() creates a nested collection of pages objects. If you have a look at the docs for groupBy() you should get the idea. Or do a dump of a grouped collection to get the idea. Note that if you group by a field, all the pages you want to group must contain that field, otherwise Kirby will throw an error.


#3

Thank you. If I can recall correctly, 'sort' is for sorting by the kirby sorting order.
//edit: I use it to keep my sorting order in panel, and not uid alphabetical order (I gess). The result is not the same without 'sort' and is correct when I keep it.

I thought that you can use only custom fields for sorting so I didn’t know that 'parent' will work out of the box!

Same for the intended templates (plus, in this case, pages share the same template)

Is there au list somewhere with parameters accepted in sortBy() ?


#4

No, there is no list, but you can sort by all fields and methods that somehow make sense to sort by plus any custom page methods or even “virtual fields” (created using map()).

Sorting by sort probably only makes sense if those pages use the same numbering scheme and if you really want to sort by their visibility flag (but that would then really mix your collections while otherwise they would be auto-sorted by parent uid, I think.