Possibility to change template in panel from select field instead of from the settings button

Hello,

is there a native possibility to change a page’s template in the panel from a, for instance, select field instead of from the settings button? (See screenshot).

My goal is to have three different pages-sections/types (see select field/screenshot), each displaying only the according subpage. Since sections can’t query subpages based on a select field, I’m filtering the subpages via template.

Thanks!

Sections:

No, that’s not possible, at least not out of the box. You could, however, use a page.update:after hook that changes the template on safe depending on the value of your select field.

Thanks for the tip!

I’m reading the hook reference, however I can’t really get the code to work. Do you maybe have a suggestion on how I can improve the code (it’s in the config file)?

'hooks' => [
        'page.update:after' => function ($page) {
          $page->update([
                'template' => $page->type()
              ]);
        }
    ]

type is the select field’s name.

You can’t use update() here, you wan to use changeTemplate() to, well, change the template.

This should work;

   'hooks' => [
        'page.update:after' => function ($newPage, $oldPage) {

            $newTemplate = $newPage->type()->value() ?? $newPage->intendedTemplate()->name();
            // lets check if the value was changed
            if ($newTemplate !== $newPage->intendedTemplate()->name()) {
                // try to change the template
                try {
                    $newPage = $newPage->changeTemplate($newTemplate);
                } catch (Exception $e) {
                    throw new Exception($e->getMessage());
                }
    
            }
        }
    ]

Make sure that you allow changing to the given set of templates in your blueprints. By default, changing to another template is disabled, because you can potentially lose data.

Also, you might want to limit the hook to certain pages or templates.

1 Like

Oh, wow, thanks so much for your help!

A short follow-up question:
We roamed the reference but couldn’t find anything. Is there a possibility to redirect a panel page to the same panel page using the update after hook? Like a page refresh.

'page.update:after' => function ($newPage, $oldPage) {
                go($newPage->url());

This didn’t work (see screenshot).

44

No, you can’t redirect from a hook or return anything. What are you trying to achieve? Is it because the template change is not reflected in the Panel?

Yes, that’s probably it. I don’t really have a solution for that.

There’s an ideas issue: https://github.com/getkirby/ideas/issues/373

1 Like

Maybe it’s a better idea to keep the same template, but use the pagesdisplay plugin instead of a standard pages section, That way, you can filter your pages by the value of the select field.

2 Likes

Thanks for the plugin, texnixe, I and my coworker will look into it!