Subpage Builder on Template Change

I use the modules plugin and modules field with a separate modules subpage. So I used the subpage builder to create this page automatically for pages with modules.

My client changed the template of a page recently and the modules page did not get created. It makes sense I guess, the subpage builder only triggers on new pages.

Is there a way I could trigger it when the template changes? With a hook maybe?

Does the subpage get deleted when the template is changed?

But yes, you could use a hook, I guess.

The subpage does not get deleted, but it’s not that bad. It’s more important to create the subpage so adding a module does not result in an error.

Since 2.4.0 I can’t even add the simplest hook without getting “An unexpected error occurred”, though. Even with an unchanged starterkit.

kirby()->hook('panel.page.update', function($page) {
  if ($page->template() == "sub" AND !$page->children()->has('modules')) {
    try {
      $page->create('modules', 'modules', array(
      	'title' => 'Module'
      ));
    } catch(Exception $e) {
    	echo $e->getMessage();
    }
  }
});

If you modify your hook a bit, it should work (line 4):

kirby()->hook('panel.page.update', function($page) {
  if ($page->template() == "sub" AND !$page->children()->has('modules')) {
    try {
      $page->children()->create('modules', 'modules', array(
      	'title' => 'Module'
      ));
    } catch(Exception $e) {
    	echo $e->getMessage();
    }
  }
});

Thanks a lot! This is working just as intended.

I’m going add a link to this thread from the GitHub issue about the recommended modules setup: https://github.com/lukaskleinschmidt/kirby-field-modules/issues/8