Skip to content

automatically call the init method on custom page classes #456

@jmartsch

Description

@jmartsch

Custom Page classes are great, but they would be even greater if we could use hooks in their init method which would be called automatically.

One thing I and others like Bernhard are doing when developing custom modules (or modifying ProcessPageEdit pages), is to add hooks to a custom page class like so:

<?php namespace ProcessWire;
// site/classes/OrderPage.php
class OrderPage extends Page{
  public function init(){
    bd("init OrderPage");
    bd($this->template->name);
    $this->addHookBefore('ProcessPageEdit::buildFormContent', $this, "buildFormContent");
  }

  public function buildFormContent($event){
    bd("buildFormContent");
    // modify the form before output
  }
}

However the init method isn't called when you go to a page with the order template (in my case in the admin).

Bernhard has a workaround where he triggers the init method of the custom page class in /site/init.php via $pages->get('template=order')->init();;

Problems with this approach are:

  • The init method would be called always, regardless if you are on a page with the template "order".
  • adds overhead as it has unnessesary calls
  • it prevents using a buildFormContent method which is different on every custom page class. For example on one template I want to use the buildFormContent method to add a field to the form, on another template I want to add a tab.

If I want to use the workaround Bernhard provided, I would have to return early manually if the template name doesn't match, like so:

public function buildFormContent(HookEvent $event)
  {
    // Change the title of the page and the browser tab
    // Get page being edited
    $page = $event->object->getPage();
    // Only use on pages with the order template
     if ($page->template != 'order') return;
   
   // else do stuff
  }

Else the hook would be executed on every page.

What you think about this, or are there other ways, to modify things like the form content in the admin via custom page classes?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions