Jump to content
louisstephens

"Add hook after save" and create child page, but do nothing after further saves

Recommended Posts

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:

  1. Create a page with a template "one".
  2. Once the page is created/saved => create a new child page with the template of "two"
  3. 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.

Edited by louisstephens
Trying to provide more clarification.

Share this post


Link to post
Share on other sites

If I understand correctly, something  like this should work, let us know if you need more detail: 

wire()->addHookekAfter("Pages:saved", function($e){
	$page = $e->arguments(0);
	if($page->template == "one"){
		$pageTwo = $page->child("template=two");
		if(!$pageTwo->id){
			//create child page code and save!
		}
	}
});

 

  • Like 3

Share this post


Link to post
Share on other sites
12 hours ago, louisstephens said:

So I have been diving into hooks lately, and I am enjoying them thus far.

Better late than never 😉 😛 

You can use Pages::added for this: https://processwire.com/api/ref/pages/added/

And using conditional hooks (https://processwire.com/blog/posts/new-ajax-driven-inputs-conditional-hooks-template-family-settings-and-more/#new-conditional-hooks) it gets even easier and cleaner:

$wire->addHookAfter('Pages::added', function(HookEvent $event) {
  $page = $event->arguments(0);
  bd($page);
});

I always start with the basic hook and test it. In this case this was quite interesting, because it fired twice! The reason is that this page contains a repeater matrix that creates a page for the first (possible) item:

DUTIhxN.png

Then you can modify the hook to be more specific:

$wire->addHookAfter('Pages::added(template=basic-page)', function(HookEvent $event) {
  $page = $event->arguments(0);
  bd($page);
});

Voila, it fires on the right page only:

LQSP92B.png

And it will not fire on any further publish/save/etc events 😉 

  • Like 5

Share this post


Link to post
Share on other sites

Thanks @bernhard! That was exactly what I was looking for. Now I'll continue down the path of learning hooks, and hopefully stop making mistakes like:

$p = new Page();
$u->template = "scripts";
$u->parent = wire('pages')->get($page->id);
$u->title = "Test";
$u->name = "test";
$u->save();

Which obviously just blows up in your face.😅

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Hardoman
      Hello community,
      we have a website running version 3.0.118. The owner would like to have a watermark merged to the images, that are being uploaded in the CKEditor as a requirement.
      Image upload besides the CKEditor within galleries and single images works as a charm already. We also use croppable image 3 there. (PIM2)
      To realize this requirement, I thought of using a hook in the admin area. So, I read a lot in our forums and tested this by adding a hook into the ready.php file.
      $this->addHookAfter('InputfieldFile::fileAdded',function(HookEvent$event){ wire('log')->save('test','Image upload works'); ... The log entry is being created correctly. But when I try to use the pim/watermark-function like in a template, he cannot find the watermark-image anymore. Furthermore, when I try to get the page-id, it does not seem to be accessible, because the application does not seem to know how to reference it, or I dont know the right way to do so…
      So my questions are:
       
      Is this the right attempt at all or will there be another, better workaround? It seems, I cannot access the page object (of the content page) within this scope or file but I would need it to save the processed image inside the right files/id folder Would it be better to place the hook into the admin-template? (or admin.php)
        Thanks for any hints in advance. 🙂
    • By martind
      hi,
      is it possible to change field parent_id from InputfieldPageListSelect to InputfieldPageAutocomplet by addHookAfter('ProcessPageEdit::buildFormContent')?
      thanks,
      martin
       
    • By Noel Boss
      👋 PW Pros…
      I have some hooks that I need to bind at the init phase (or even __construct) and I was wondering, and I couldn't find a good and simple way to determine if I'm in the admin. Would be nice if there is a reliable short option to do so, but I can't seem to find one… Is there a coherent way to tell this no matter where I am?
      Right now, I use the following method inside one of my modules:
      public function isAdmin($page = null) { if ( strpos($this->input->url, $this->urls->admin) !== false || $this->process instanceof ProcessPageList || $this->process instanceof ProcessPageEdit || ($page instanceof Page && $page->rootParent->id == $this->config->adminRootPageID) ) { return true; } return false; } @ryan wouldn't it be nice to have something like wire()->isAdmin(); like wire()->user->isLoggedin(); to tell if we are in admin – very early on (probably even in __construct() phase of modules?
    • By jom
      Hi everyone
      It seems that I don't fully understand the wireTempPath() function and I need some help.
      I use wireTempPath() to create a new location in assets/cache/WireTempDir and than copy a pdf from the assets/files/page folder to the new folder. I want the file to be accessible only for a limited time, that's why I use wireTempPath.
      The file seems to be copied to the right location, but gets deleted right afterwards, according to 
      As mentioned in the topic above, 
      $wireTempDir->setRemove(false); prevents the file to be deleted. But I like the file to be automatically deleted after a few days. So, how can I do that?
      My code so far (everything works, but the automatic removal of the tempDir folder):
      //generate and show download link $folder = time(); // timestamp as temporary folder $maxAge = (int) $settings->options_downloadlink_valid_hours * 3600; //tempDir wants maxAge as seconds $options = array( 'maxAge' => $maxAge ); $wireTempDir = wireTempDir($folder, $options); $wireTempDir->setRemove(false); $src_file = $page->ebook_download->filename; // Create a new directory in ProcessWire's cache dir if(wire('files')->mkdir($wireTempDir, $recursive = true)) { if(wire('files')->copy($src_file, $wireTempDir)){ //get subdirs from tempDir: $pos = strpos($wireTempDir, "WireTempDir"); $subdir = substr($wireTempDir, $pos, 100); $out .= "<p><a href='" . wire('pages')->get('template=passthrough')->httpUrl . "?file=" . $subdir . $page->ebook_download->basename . "' target='_blank'>$page->title</a></p>"; } } I appreciate any ideas - thanks!
      Oliver
    • By VeiJari
      Hello forum, this is my first security related post, so I'm a bit of a newbie.
      I understand that when I have direct front-input from user I should sanitize the input, but how about when I use a secret key for showing a API for a third-party supplier? Should I sanitize the input->get() key?
      I've tested this issue and I tried ?key=<?php echo $page->field; ?> And without adding any sanitization it comes back: /?key=<?php%20echo%20$page->field;%20?>
      So can I rely on this, or should I still use $sanitizer just in case?
       
      Thanks for the help!
×
×
  • Create New...