Jump to content

Recommended way for creating a page reference field (using "select" inputfield) for repeater pages and avoiding unnecessary page loads


Recommended Posts

Posted

There may be a time where you need to create a page reference field using the Select inputfield and it's selecting repeater pages.

Let's say I have a repeater field called "order_line_items" and I want to create a page reference field called "order_line_item" that allows me to select a repeater item (which is a page) of the "order_line_items" repeater field.

Repeater pages are a bit different from regular pages in that their "parent" is a container admin page associated with the page in which it exists (dig into /admin/repeaters/order_line_items/ in your page tree to see what I mean).  So when you are configuring your page reference field, you can't really choose a Parent.  However when configuring your field, your instinct would be to choose the Template of "repeater_order_line_items".

Then because you need extra precision in what pages are actually available for selection (rather than all of them across all pages), your instinct will be to implement custom PHP code:

$wire->addHookAfter('InputfieldPage::getSelectablePages', function($event) {
  if($event->object->hasField == 'order_line_item') {
    $event->return = $event->pages->find('your selector here');
  }
});

The problem with that approach is that even though you have defined the custom PHP code and the select field correctly shows the selectable repeater pages in the select field, behind-the-scenes, ProcessWire has still loaded EVERY SINGLE REPEATER that has the "repeater_order_line_items" template (you can see this is TracyDebugger's pages loaded list)!  Your site will definitely be slower as a result, dramatically so if you have thousands or tens of thousands of repeater pages of that template.

I hit this issue years ago (2018) and I thought it was a bug.  I discussed it with Ryan and it's technically not a bug, but kind of the way ProcessWire works, which is beyond this tutorial.

While you can circumvent this using the PageAutocomplete field, I don't like the ergonomics of that field in certain situations.  I want the good-old select field.

The solution to this is to NOT select anything for the "Template" when configuring your field.  So in my example, I chose "repeater_order_line_items", but instead, it should be left blank.

Now the field will just rely on the code portion and all the unnecessary page loads will be eliminated.

  • Like 9

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
  • Recently Browsing   0 members

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