Jump to content
Mathroth

AddHookAfter("save"...) on Page template ==("")

Recommended Posts

Greetings to all processwire fans,

I am new in processwire and I have used it since 3 weeks. Probably it's a really silly question but does someone now how I can execute a function in my own module, which is triggered when I save a pages, which contains a user-defined template. I tried to to this with an basic if/else condition to trigger the hook when the page has theTemplateName== "". Unfortunately it doesn't work. So I try this which might be the wrong Syntax. Perhaps someone can give me a hint ;) THANKS a lot! 

 

    public function init() {

        // add a hook after the $pages->save, to issue a notice every time a page is saved
   
        $this->page->template == "templateName"->addHookAfter('save', $this, 'example1');
 
    }

 

Share this post


Link to post
Share on other sites

Hi, welcome to PW forums.

Looks like you have not the right PHP syntax. Try this:

public function init() {
    // you need a condition that will result to true
    if($this->page->template->name == 'templateName') {
		$this->addHookAfter('save', $this, 'example1');
    }
}

 

  • Like 1

Share this post


Link to post
Share on other sites
12 minutes ago, horst said:

Hi, welcome to PW forums.

Looks like you have not the right PHP syntax. Try this:


public function init() {
    // you need a condition that will result to true
    if($this->page->template->name == 'templateName') {
		$this->addHookAfter('save', $this, 'example1');
    }
}

 

Thanks for your help! Seems to be the right syntax now but unfortunately the function will not be fired. I also tried different templates...:'(

Share this post


Link to post
Share on other sites

The page object is not available in init(). You need to use ready()

  • Like 1

Share this post


Link to post
Share on other sites
6 minutes ago, adrian said:

The page object is not available in init(). You need to use ready()

public function ready() {
        if($this->page->template->name == 'TemplateName') {
            $this->addHookAfter('save', $this, 'syncMobileDE');
        }
    }

Also tried this. No function execution :( 

Share this post


Link to post
Share on other sites

Needs the Pages class in there somewhere. Either:

public function ready() {
    if($this->page->template->name == 'TemplateName') {
        $this->pages->addHookAfter('save', $this, 'syncMobileDE');
    }
}

Or:

public function ready() {
    if($this->page->template->name == 'TemplateName') {
        $this->addHookAfter('Pages::save', $this, 'syncMobileDE');
    }
}

 

  • Like 2

Share this post


Link to post
Share on other sites
1 hour ago, Robin S said:

Needs the Pages class in there somewhere. Either:


public function ready() {
    if($this->page->template->name == 'TemplateName') {
        $this->pages->addHookAfter('save', $this, 'syncMobileDE');
    }
}

Or:


public function ready() {
    if($this->page->template->name == 'TemplateName') {
        $this->addHookAfter('Pages::save', $this, 'syncMobileDE');
    }
}

 

Unfortunately not! :-[ It just works if I save any of the pages – regardless which template the page is using. 

 public function init() {
        $this->pages->addHookAfter('Pages::save', $this, 'syncMobileDE');
}

 

Share this post


Link to post
Share on other sites
9 hours ago, Mathroth said:

Unfortunately not! :-[ It just works if I save any of the pages – regardless which template the page is using. 


 public function init() {
        $this->pages->addHookAfter('Pages::save', $this, 'syncMobileDE');
}

You have to perform the check for the template name inside your hook function. $this->page or wire('page') returns whatever page in which the module code is executed (admin page editor, custom page with the code...). Pages::save on the other hand is called with the page object being saved, which is what you're looking for.

public function init() {
        $this->pages->addHookAfter('Pages::save', $this, 'syncMobileDE');
}

protected function syncMobileDE(HookEvent $event) {
	$page = $event->arguments(0);
	if($page->template->name == 'TemplateName') {
		// Run your code
	}
}

 

  • Like 6

Share this post


Link to post
Share on other sites
On 3.4.2017 at 8:50 AM, BitPoet said:

You have to perform the check for the template name inside your hook function. $this->page or wire('page') returns whatever page in which the module code is executed (admin page editor, custom page with the code...). Pages::save on the other hand is called with the page object being saved, which is what you're looking for.


public function init() {
        $this->pages->addHookAfter('Pages::save', $this, 'syncMobileDE');
}

protected function syncMobileDE(HookEvent $event) {
	$page = $event->arguments(0);
	if($page->template->name == 'TemplateName') {
		// Run your code
	}
}

 

You made my day, now it works. Looks very logical and works quite well. Thanks to all for your advises. Have a nice weekend! 

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By jploch
      Hi folks,
      i try to use a hook to change some markup inside admin, this hook works fine inside a ready.php file, but its not working inside my module:
      <?php namespace ProcessWire; class InputfieldPageTableExtendedGrid extends InputfieldPageTable { public static function getModuleInfo() { return array( 'title' => __('Inputfield for PageTableExtendedGrid', __FILE__), // Module Title 'summary' => __('Adds Inputfield for PageTableExtendedGrid', __FILE__), // Module Summary 'version' => 233, 'requires' => array('FieldtypePageTableExtendedGrid'), 'permanent' => false, ); } public function ready() { $this->addHookAfter('Page::render', function($event) { $value = $event->return; // Return Content $style = "<style type='text/css'>". $this->pages->get((int) wire('input')->get('id'))->style ."</style>"; // Add Style inside bottom head $event->return = str_replace("</head>", "\n\t$style</head>", $value); // Return All Changes }); } } whats wrong here?
    • By Sten
      Hello
      Till now I hacked something with the twig template but it works no more with new PW versions so I look forward to create a module. I am working on a site in multiple languages : French, English, Italian, German, Spanish, Portuguese, Hebrew, Russian. The new posts are entered in any language with a field for language. Till now, I got twig files to get the translations with constants defined for each part of the pages.
      So I'd like to create a module to include theses files added according to the url /fr/en/...
      Have you some observations to do before I begin about the direction to take ?
      Thank you
    • By gebeer
      Hello all,
      wasn't sure where to put this, so it goes in General section.
      Ryan shows a hook that we can use to mirror files on demand from live server to development environment to be up to date with the files on the server without having to download complete site/assets/files folder.
      I just implemented this but had problems getting files to load from a site in development that is secured with user/password via htaccess.
      First I tried to use WireHttp setHeader method for basic authentication like this
      function mirrorFilesfromLiveServer(HookEvent $event) { $config = $event->wire('config'); $file = $event->return; if ($event->method == 'url') { // convert url to disk path $file = $config->paths->root . substr($file, strlen($config->urls->root)); } if (!file_exists($file)) { // download file from source if it doesn't exist here $src = 'http://mydomain.com/site/assets/files/'; $url = str_replace($config->paths->files, $src, $file); $http = new WireHttp(); // basic authentication $u = 'myuser'; $pw = 'mypassword'; $http->setHeader('Authorization: Basic', base64_encode("$u:$pw")); $http->download($url, $file); } } But, unfortunately this didn't work.
      So now I am using curl to do the download. My hook function now looks like this
      function mirrorFilesfromLiveServer(HookEvent $event) { $config = $event->wire('config'); $file = $event->return; if ($event->method == 'url') { // convert url to disk path $file = $config->paths->root . substr($file, strlen($config->urls->root)); } if (!file_exists($file)) { // download file from source if it doesn't exist here $src = 'http://mydomain.com/site/assets/files/'; $fp = fopen($file, 'w+'); // init file pointer $url = str_replace($config->paths->files, $src, $file); $u = 'myuser'; $pw = 'mypassword'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 50); // crazy high timeout just in case there are very large files curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, "$u:$pw"); // authentication curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // authentication curl_setopt($ch, CURLOPT_FILE, $fp); // give curl the file pointer so that it can write to it curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $data = curl_exec($ch); curl_close($ch); } } Now I can load files and images from the htaccess protected development server 🙂
      If anyone knows how to get this to work with WireHttp, please let me know. Thank you.
    • By Guy Incognito
      I've created a simple sports league fixture generator in a template called 'League'. Teams are added as page references then a fixture list is created as a ProFields table by hooking page save to add new rows to the table.
      The bit I need help with is that I'm trying to check a fixture doesn't already exist before adding it to the table (e.g. if a new team is added to the league). I'm trying to do this with a PW selector to filter the fixtures table and check whether Team A vs Team B already exists in the table. Then on the next line checking no fixture was found by using count().
      However as soon as I add the selector the script no longer adds any rows to the table. If I take it out, it all works fine (albeit with duplicate fixtures each time the page is saved). I've also tested the selector in a page template and it filters as expected. It's late here (UK)... I'm probably doing something stupid! Any ideas?
      <?php //Hook page save to generate league fixture lists $wire->addHookAfter("Pages::saved(template=league)", function ($event) { //Get which page has been saved $page = $event->arguments(0); $noFixturesAdded = 0; //For each team in league cycle through and add home fixtures foreach ($page->teams_in_league as $teamA) { foreach ($page->teams_in_league as $teamB) { //Check if fixture already exists $existingFixtures = $page->fixtures("team_a=$teamA,team_b=$teamB"); //Check team A is not the same as team B as you can't play yourself //Then add row to fixture table if ($teamB != $teamA && $existingFixtures->count() < 1 ) { $fixture = $page->fixtures->makeBlankItem(); $fixture->team_a = $teamA->id; $fixture->team_b = $teamB->id; $page->fixtures->add($fixture); $noFixturesAdded ++; } } } //Save updates to table $page->save('fixtures'); $message = "League saved. $noFixturesAdded new fixtures were added"; $this->message($message); });  
×
×
  • Create New...