Jump to content

Getting started with hooks


deltavik
 Share

Recommended Posts

So I thought of hooking up with hooks. I installed that "hello world" module, and now, when I save a page, I see "Hello world..." message on top -- which makes sense. To play with it further, I copied the hook code from the module to my header.php file.

The code is: 

$pages->addHookAfter('save', $this, 'example1');

function example1($event) {
    $page = $event->arguments[0];
    $this->message("Hello World 2 ! You saved {$page->path}.");
}

It is a verbatim copy of the code from the module, and it is placed in a file that gets called first via prependTemplateFile in config.php. 

However, now when I save a page, I don't see the message from my hook function. What could I be missing?

thanks,

Link to comment
Share on other sites

What say the doc :

Quote

The $config->prependTemplateFile is not used by the ProcessWire admin, so if you are defining hooks specific to the ProcessWire admin, you should define them at the very top of the /site/templates/admin.php. If your hooks are applicable to both your site (front-end) and the ProcessWire admin, then you should manually include your sites initialization fie, i.e. include("./_init.php"); from your /site/templates/admin.php file.

 

also $this is not callable in this context as you're not in an object.

In order to get the hook working, you should write the hook in _init.php  :

function example1(HookEvent $event) {
    $page = $event->arguments[0];
    wire('session')->message("Hello World 2 ! You saved {$page->path}");
}
$pages->addHookAfter('Pages::save', null, 'example1');

And in admin.php, add :

include("./_init.php");

 

Now go to in backend, and save a page, the message 'Hello World 2 ! You saved /your/page/' should appear.

 

  • Like 2
Link to comment
Share on other sites

  • 4 years later...

Thanks, this was helpful for me. Just one notice:

To get out the message, "wire('session')" was not working for me, I used $this instead:

function example1(HookEvent $event) {
    $page = $event->arguments[0];
    $this->message("Hello World 2 ! You saved {$page->path}");
}
$pages->addHookAfter('Pages::save', null, 'example1');

 

  • 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

×
×
  • Create New...