Jump to content

Sorting pages in the page tree via hook – unexpected order


a-ok
 Share

Recommended Posts

I thought this would be fairly trivial but it's not giving the expected results.

I want to sort a parent/child set up in the admin page tree (I need to sort by multiple selectors, which the admin doesn't allow, so doing it via a hook)

This is what I have as my hook:

function hookPageTreeFind(HookEvent $event) {

    $page = $event->arguments('page');
    if ($page->template->name == 'projects-overview') {

        foreach($page->children() as $child) {

            if ($child->detail_dates_date_sort === '') {
                $child->detail_dates_date_upcoming = $child->getUnformatted('created');
                bd($child->title . ' ' . date('l j F Y', $child->detail_dates_date_upcoming));
            } else {
                $child->detail_dates_date_upcoming = $child->getUnformatted('detail_dates_date_sort');
                bd($child->title . ' ' . date('l j F Y', $child->detail_dates_date_upcoming));
            }
        }

        $event->return = $page->children("sort=detail_dates_date_upcoming");
        bd($event->return);

    }

}
wire()->addHookAfter('ProcessPageList::find', null, 'hookPageTreeFind');

It loops through each child page and grabs the date field 'detail_dates_date_sort' and sets that as the sort value. The date field is sometimes left blank so I set the sort value as the created date.

I'm doing a bit of debugging (hence the bar dumps) and you can see from this screenshot that the order is messed up? The child at the end of the screenshot 'Black Quantum Futurism' has no date field set so thus outputting, correctly, the created date.

Any pointers to where I'm going wrong? Thanks.

Link to comment
Share on other sites

Turns out I had to set the sort before the return...

if ($page->template->name == 'projects-overview') {

		foreach($page->children() as $child) {

			if ($child->detail_dates_date_sort === '') {
				$child->detail_dates_date_upcoming = $child->getUnformatted('created');
			} else {
				$child->detail_dates_date_upcoming = $child->getUnformatted('detail_dates_date_sort');
			}
		}

		$page->children()->sort('-detail_dates_date_upcoming');

		$event->return = $page->children();

	}

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...