creativejay

New to Hooks, trying to wrap my head around the syntax

Recommended Posts

I really wanted to create this post with some sample code to show that I at least tried to figure it out on my own first, but I'm really struggling with how hooks are even written. I know it's a very simple context for anyone who's already using them (and hopefully it will be for me, soon), but this is my first time.

What I'm trying to achieve in this attempt is to verify/change the name and title fields of a page, of one specific template with one specific field, whenever the page is saved.

Initially, I am using the Family / Name Format for Children to skip the name/title/confirm save page when an author creates a new page in my site using kongondo's ProcessBlog module.

In English, I want to: Detect when a page of template blog_page is saved with the blog_categories field value of Swatch, and replace the title and name string with a concatenated version of the following fields (from the same page): blog_date, createdUser, blog_brand and blog_name.

From what I've read so far, I should build this hook into site/templates/admin.php, and I should use the saveReady() and maybe saveField() hooks. Other than knowing I need to define a custom hook, I really haven't got any idea of where to go from here. 

Here's my mangled first attempt at coding my hook. Hopefully you'll be able to tell how I might be misunderstanding this from the following:

$pages->addHookAfter('saveReady', $this, 'myPageRename);

public function myPageRename($event) {
 }

I'm afraid that's really as far as I've gotten because I have no idea what I'm doing. I try to follow examples but they feel really far removed from context for me.

Thanks for any light that can be shed on this!

Share this post


Link to post
Share on other sites

There's a really great and simple example given by ryan here that can help you understand.

In your case, you should be able to do the following (not tested):

$pages->addHook('saveReady', function($event) {
  $sanitizer = wire('sanitizer');
  $pages = $event->object;
  $page = $event->arguments(0); 
  if($page->template == 'blog_page' && $page->blog_categories == 'Swatch') {
    // You can build the string as you wish, here is an example
    $concatenatedName = $page->blog_date;
    $concatenatedName .= '-' . $page->createdUser;
    $concatenatedName .= '-' . $page->blog_brand;
    $concatenatedName .= '-' . $page->blog_name;

    $page->title = $concatenatedName;
    $page->name = $sanitizer->pageName($concatenatedName);
  }
});
  • Like 2

Share this post


Link to post
Share on other sites

I find it easier to manage these things in a module like this. Also you need to use a before hook, as saving the page with the new title after saving would trigger an infinite loop. See next posts

<?php

/**
 * ProcessWire 'Hello world' demonstration module
 * 
 * ProcessWire 2.x 
 * Copyright (C) 2014 by Ryan Cramer 
 * Licensed under GNU/GPL v2, see LICENSE.TXT
 * 
 * http://processwire.com
 *
 */

class PutYourNameHere extends WireData implements Module {

	/**
	 * getModuleInfo is a module required by all modules to tell ProcessWire about them
	 *
	 * @return array
	 *
	 */
	public static function getModuleInfo() {

		return array(
			'title' => '', 
			'version' => 1, 
			'summary' => '',
			'singular' => true, 
			'autoload' => true,
			);
	}

	public function init() {
		$this->addHookAfter('Pages::saveReady', $this, 'doStuffOnPage'); 
	}

	public function doStuffOnPage($event) {
		$page = $event->arguments[0]; 

		if($page->template->name === "blog_page" && $page->blog_categories == "Swatch"){
			// Do your thing
		}
	}
	
}

  • Like 3

Share this post


Link to post
Share on other sites

I find it easier to manage these things in a module like this. Also you need to use a before hook, as saving the page with the new title after saving would trigger an infinite loop.

Thank you! So using the string code from @ESRCH in the "//Do your thing" line of your example, I would then install this module in my site and then it will automatically run, or do I need to call it from somewhere else as well?

Share this post


Link to post
Share on other sites

Exactly. You just would do good in renaming the module and placeing it in a file like ModuleClassName.module and mostly it's a good idea to pack it in a folder with this name, too. 

Edit:

Just for your education: The "autoload" config tells processwire to load the module everytime. 

Also you could use this to alert the user in the admin about the modules activity. This will generate a message, e. g. like the one telling you the page has been saved.

$this->message("Changed title according to settings in …");

Share this post


Link to post
Share on other sites

Putting this in a separate module is indeed cleaner.

You probably already read these pages, but I'm putting the links here just in case, since they really helped me develop my own modules/hooks:

https://processwire.com/api/hooks/

http://wiki.processwire.com/index.php/Module_Creation

Also, the Helloworld Module in /site/modules is a great example module to get going.

Share this post


Link to post
Share on other sites

Very good advice from soma (as always).

This is what I usually do:

$this->addHookAfter('Pages::saveReady', $this, 'renameBeforeSave');

public function renameBeforeSave(HookEvent $event) {
        $p = $event->arguments[0];
        $p->name = $new_name;
        $event->return = $p; // maybe this isn't actually needed - haven't tested and can't remember 
        //as soma mentioned - this last line definitely isn't needed!
}

Of course you'll need to add in your logic to limit by template/category and to build up the new name/title.

Share this post


Link to post
Share on other sites

Actually saveReady is an after hook and it's especially useful as you know that the page is saved right after that. So no endless recursion and you don't need to save the page. With a before save hook you don't know if an error will occur.

Also no need to set the page back to the argument after you done with manipulating the page. So lots of mis-infos here..

Means the best answer isn't the best really :P

Edit: removed the 'Solved' flag for now.

  • Like 1

Share this post


Link to post
Share on other sites

No need for the event->return = $p or anything like that, Adrian ;)

Share this post


Link to post
Share on other sites

No need for the event->return = $p or anything like that, Adrian ;)

Yeah, looks like my comment about that crossed with your correction :)

Share this post


Link to post
Share on other sites

@Soma

I updated my post to reflect this as there could easily be people just copying the whole thing.

Share this post


Link to post
Share on other sites

@adrian here's the module I made from your code. I'm getting a unexpected T_VARIABLE, expecting T_FUNCTION (line 55) - that would be on "public function renameBeforeSave(HookEvent $event) {"

<?php

/**
 * ProcessWire 'Rename Page' module by forum user creativejay
 *
 * Checks to see if a page uses the template "blog-post" and has a $page->blog_categories value of "Swatch" then redefines the value of $page->title and $page->name
 * 
 * 
 * ProcessWire 2.x 
 * Copyright (C) 2014 by Ryan Cramer 
 * Licensed under GNU/GPL v2, see LICENSE.TXT
 * 
 * http://processwire.com
 *
 */

class RenamePage extends WireData implements Module {

	/**
	 * getModuleInfo is a module required by all modules to tell ProcessWire about them
	 *
	 * @return array
	 *
	 */
	public static function getModuleInfo() {

		return array(

			// The module's title, typically a little more descriptive than the class name
			'title' => 'Rename Page', 

			// version number 
			'version' => 3, 

			// summary is brief description of what this module is
			'summary' => 'Checks to see if a page uses the template blog-post and has a blog_categories value of Swatch then redefines the value of title and name',
			
			// Optional URL to more information about the module
			'href' => 'https://processwire.com/talk/topic/8863-new-to-hooks-trying-to-wrap-my-head-around-the-syntax/',

			// singular=true: indicates that only one instance of the module is allowed.
			// This is usually what you want for modules that attach hooks. 
			'singular' => true, 

			// autoload=true: indicates the module should be started with ProcessWire.
			// This is necessary for any modules that attach runtime hooks, otherwise those
			// hooks won't get attached unless some other code calls the module on it's own.
			// Note that autoload modules are almost always also 'singular' (seen above).
			'autoload' => true, 
		
			// Optional font-awesome icon name, minus the 'fa-' part
			'icon' => 'eraser', 
			);
	}
$this->addHookAfter('Pages::saveReady', $this, 'renameBeforeSave');

public function renameBeforeSave(HookEvent $event) {
        if($page->template->name === "blog_post" && $page->blog_categories == "Swatches"){
        	$concatenatedName = $page->blog_date;
		    $concatenatedName .= '-' . $page->createdUser;
		    $concatenatedName .= '-' . $page->blog_brand;
		    $concatenatedName .= '-' . $page->blog_name;
		    
			$concatenatedTitle = $page->blog_brand;
		    $concatenatedTitle .= ' ' . $page->blog_name;
		
		    $page->title = $concatenatedTitle;
		    $page->name = $sanitizer->pageName($concatenatedName);
		    }
        $event->arguments[0] = $page;
}

Can you spot what I've done wrong?

Share this post


Link to post
Share on other sites

You need to add the hook in the init function as you can see it done in my first post here. The thing you're writing there is a class, these can only hold properties and functions and not raw code, like you did. It's only there to provide functionality, which can be called later. The init function of a module is always called on loading the module.

  • Like 1

Share this post


Link to post
Share on other sites

Try this:

<?php

/**
 * ProcessWire 'Rename Page' module by forum user creativejay
 *
 * Checks to see if a page uses the template "blog-post" and has a $p->blog_categories value of "Swatch" then redefines the value of $p->title and $p->name
 * 
 * 
 * ProcessWire 2.x 
 * Copyright (C) 2014 by Ryan Cramer 
 * Licensed under GNU/GPL v2, see LICENSE.TXT
 * 
 * http://processwire.com
 *
 */

class RenamePage extends WireData implements Module {

    /**
     * getModuleInfo is a module required by all modules to tell ProcessWire about them
     *
     * @return array
     *
     */
    public static function getModuleInfo() {

        return array(

            // The module's title, typically a little more descriptive than the class name
            'title' => 'Rename Page', 

            // version number 
            'version' => 3, 

            // summary is brief description of what this module is
            'summary' => 'Checks to see if a page uses the template blog-post and has a blog_categories value of Swatch then redefines the value of title and name',
            
            // Optional URL to more information about the module
            'href' => 'https://processwire.com/talk/topic/8863-new-to-hooks-trying-to-wrap-my-head-around-the-syntax/',

            // singular=true: indicates that only one instance of the module is allowed.
            // This is usually what you want for modules that attach hooks. 
            'singular' => true, 

            // autoload=true:indicates the module should be started with ProcessWire.
            // This is necessary for any modules that attach runtime hooks, otherwise those
            // hooks won't get attached unless some other code calls the module on it's own.
            // Note that autoload modules are almost always also 'singular' (seen above).
            'autoload' => true, 
        
            // Optional font-awesome icon name, minus the 'fa-' part
            'icon' => 'eraser', 
            );
    }
    
    public function init() {
        $this->addHookAfter('Pages::saveReady', $this, 'renameBeforeSave');
    }

    public function renameBeforeSave(HookEvent $event) {

        $p = $event->arguments[0];

        if($p->template->name === "blog_post" && $p->blog_categories == "Swatches"){
            $concatenatedName = $p->blog_date;
            $concatenatedName .= '-' . $p->createdUser;
            $concatenatedName .= '-' . $p->blog_brand;
            $concatenatedName .= '-' . $p->blog_name;
            
            $concatenatedTitle = $p->blog_brand;
            $concatenatedTitle .= ' ' . $p->blog_name;
        
            $p->title = $concatenatedTitle;
            $p->name = $sanitizer->pageName($concatenatedName, true);
        }
    }
}

Share this post


Link to post
Share on other sites

Okay, I fixed the mismatched names inside the code (I changed the name to RenameSwatches a few times but the code was still referring to RenamePages). That fixed the 500 error, but nothing happens when I save an existing page.

I suppose I could add a dialog to see if it thinks it's running.

Another thought occurs to me.. the field blog_categories is a Page fieldtype. Would that require an adjustment?

Share this post


Link to post
Share on other sites

Another thought occurs to me.. the field blog_categories is a Page fieldtype. Would that require an adjustment?

// Page field single
if($page->blog_categories->title === "Swatch"){
}

// Page field multiple
if($page->blog_categories->get("title=Swatch")){
}

Share this post


Link to post
Share on other sites

There's a lot not right in your renameBeforeSave method. Naming is also a little bit weird:

You hook after, but you call the method with before in the name.

$p->blog_categories == "Swatches" // If blog_categories is type of page it will not be a string.

$p->createdUser // is a Page // you can't concatenate it like this.

You can't call $sanitizer like this in module scope. (use $this->sanitizer)

Share this post


Link to post
Share on other sites

$p->blog_categories->title ?

$p->createdUser->title ?

And I should turn $p->blog_date into a string, I imagine?

Share this post


Link to post
Share on other sites

$p->blog_categores->title == 'Swatch';

For the $p->createdUser, you can actually still use $p->createdUser, since the toString method of the page will convert it to its page id.

Share this post


Link to post
Share on other sites

blog_categories is a Multiple Page field. This will not work $p->blog_categories == 'swatch'; This has been pointed out above with example code by LostKobrakai.

Edit - see next post...

Edited by kongondo

Share this post


Link to post
Share on other sites

@kongondo your default blog_categories is, but I changed it to a Single Page field because of the way my (already familiarly strange to you) blog is structured. ;)

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 Harmen
      I want to add a few pages to an AsmSelect Page field inside a repeater using the following code:
      $trialsPage = wire("pages")->get(28422); // Get the page $trialsPage->of(false); $newTrial = $ordersPage->trial_repeater_orders->getNewItem(); // Add item to repeater foreach ($selectedProducts as $selectedProduct){ $productPage = $pages->get("template=product, reference=$selectedProduct"); $newTrial->trial_selected_products->add($productPage); } $newTrial->save(); $trialsPage->save(); However, when I check the page where the field is located it doesn't have the new values as expected. The selected pages exist, the field is in the right location, made sure that the output formatting is turned off: $page->of(false); But it still doesn't work with a variable. No matter what I try, it doesn't work.
      It only works when I replace $selectedProduct with a hardcoded string. Am I doing something wrong here?
    • By louisstephens
      So I have been diving into hooks lately, and I am enjoying them thus far. However, I guess I am a bit stumped on how to achieve what I want too. I am trying to set up a hook that would create a new child page when the parent page is saved. However, when you save the parent page a second time, I just need to update the child page without creating multiple child pages. What would be the best way to go about this?
      So after rereading my post, I believe it is a bit vague so I will try to explain more. 
      The Goal:
      Create a page with a template "one". Once the page is created/saved => create a new child page with the template of "two" If the parent is saved anytime after, do nothing to the child page (limit the parent page to one child page) The parent page is really just being used to output content, whereas the child page is being used to pull out the some fields from the parent to be used elsewhere. I might have made this too complicated in my head.
    • By Peter Knight
      Is there a way to make JPGs progressive by default via the API?
      I've added the following to my site/config.php file but user-uploaded images are often displayed as non progressive.
      $config->imageSizerOptions = array( 'upscaling' => true, // upscale if necessary to reach target size? 'cropping' => true, // crop if necessary to reach target size? 'autoRotation' => true, // automatically correct orientation? 'interlace' => true, // use interlaced JPEGs by default? (recommended) 'sharpening' => 'soft', // sharpening: none | soft | medium | strong 'quality' => 95, // quality: 1-100 where higher is better but bigger 'hidpiQuality' => 60, // Same as above quality setting, but specific to hidpi images 'defaultGamma' => 0.5, // defaultGamma: 0.5 to 4.0 or -1 to disable gamma correction (default=2.0) ); Thanks
    • By louisstephens
      From my last post, I was given a good idea on how to count the repeater items, and it worked wonderfully. I got my code working well and the columns (based on the count) all work well as well. Now, I have a head scratcher on my hands. 
      <?php $buttonsIncluded = $page->special_custom_buttons->find('special_custom_buttons_include=1'); $buttonsIncludedCount = count($buttonsIncluded); $buttonsIncludedCountAdditional = $buttonsIncludedCount +1; echo $buttonsIncludedCount; ?> <div class="row"> <?php foreach($buttonsIncluded as $button): ?> <?php if($button->custom_buttons_include): ?> <?php if($buttonsIncludedCountAdditional == 2): ?> <div class="col-6"> <a href=""><?php echo $button->custom_buttons_text; ?></a> </div> <?php elseif($buttonsIncludedCountAdditional == 3): ?> <div class="col-4"> <a href=""><?php echo $button->custom_buttons_text; ?></a> </div> <?php elseif($buttonsIncludedCountAdditional == 4): ?> <div class="col-3"> <a href=""><?php echo $button->custom_buttons_text; ?></a> </div> <?php endif; ?> <?php endif; ?> <?php endforeach; ?> </div> All of this is included in a larger foreach statement that is pulling in other data (like body copy etc etc) from a Page Table field. As you can see in my code above, I am adding "1" to the count, so I can have space in the grid layout for a new button.
      So, right now: it looks something like: 
      [repeater button] [repeater button] [repeater button] [space for new button] What I really need to do is to pull in the button from the Page Table and add it into the new space so it looks like:
      [repeater button] [repeater button] [repeater button] [button from Page Table] Is this even possible todo, or is there a better way to go about this? 
       
      *Edit*
      So, I really just overlooked something quite easy here. Since the grid is based on 12 columns, I could just take 12 and divide by $buttonsIncludedCountAdditional which would give me the remaining col width to use outside the foreach loop. I was trying to make this too complicated.