Jump to content
VeiJari

How to programmatically change page name after saving it?

Recommended Posts

Hello forum!

I've yet again stumbled on a head-scratching situation. We have enabled the option on our articles template and events template that it skips the title adding part and goes straight to the form. This is what our customer wants. So when you add a new article or event it automatically names it temporary to "article-0000000" and same with event. Now the problem is that obviously after saving the form we want to change to page url or "name" to the title, like it's normally. 

Now here's the code for the hook:

wire()->addHookBefore("Pages::saved(template=tapahtuma|artikkeli)", function($hook) {
  $page = $hook->arguments(0);
  $newUrl = wire()->sanitizer->pageName($page->title); // give it a name used in the url for the page
  wire()->log->message($page->name);
  $page->setAndSave('name', $newUrl);
});

I get the correct page and the name and path changes when I log them, but when I try to save it. It just loads and then I get: 

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) This happens in sanitizer.php

and then another error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0

 

What is happening? Am I not suppose to use sanitizer in this way? When we made a temporary page object in out other hook, the sanitizer worked perfectly.

Thanks for the help!

Share this post


Link to post
Share on other sites

You're creating an infinite loop. You hook into "after save" change something and save again, which again triggers your "after save" hook and so on. Either look for another hook to do your work (potentially change things last minute before the actual save) or add some way for your hook to only run once and not for the saves it initiated on it's own.

  • Like 2

Share this post


Link to post
Share on other sites

@VeiJari maybe hook after pages::saveReady is better for this. But also it is possible in a pages::saved hook to save the page again without running into an infinite loop with, for example, using a temporary property:

wire()->addHookBefore("Pages::saved(template=tapahtuma|artikkeli)", function($hook) {
	$page = $hook->arguments(0);
	if($page->skipMyHook) {             // if the page already has our temporary property, we skip further processing
		return;
	}
	$newUrl = wire()->sanitizer->pageName($page->title); // give it a name used in the url for the page
	wire()->log->message($page->name);
	$page->skipMyHook = true;           // add a temporary property to the page (it is only in memory)
	$page->setAndSave('name', $newUrl);
});

 

  • Like 1

Share this post


Link to post
Share on other sites
2 hours ago, LostKobrakai said:

You're creating an infinite loop. You hook into "after save" change something and save again, which again triggers your "after save" hook and so on. Either look for another hook to do your work (potentially change things last minute before the actual save) or add some way for your hook to only run once and not for the saves it initiated on it's own.

Ah, silly me 😄 Of course I didn't think the obvious.

It now works and I'm using this module: https://modules.processwire.com/modules/page-rename-options/ for all the pages at the moment!

Thanks anyway!

37 minutes ago, horst said:

@VeiJari maybe hook after pages::saveReady is better for this. But also it is possible in a pages::saved hook to save the page again without running into an infinite loop with, for example, using a temporary property:


wire()->addHookBefore("Pages::saved(template=tapahtuma|artikkeli)", function($hook) {
	$page = $hook->arguments(0);
	if($page->skipMyHook) {             // if the page already has our temporary property, we skip further processing
		return;
	}
	$newUrl = wire()->sanitizer->pageName($page->title); // give it a name used in the url for the page
	wire()->log->message($page->name);
	$page->skipMyHook = true;           // add a temporary property to the page (it is only in memory)
	$page->setAndSave('name', $newUrl);
});

 

Ah I see! Good to know, might be handy someday for preventing those pesty infinite loops 😄

Thanks horst

  • 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 Robin S
      Sanitizer EasySlugger
      Allows the use of the EasySlugger library as Sanitizer methods.
      Installation
      Install the Sanitizer EasySlugger module.
      Usage
      The module adds four new sanitizer methods.
      slugger($string, $options)
      Similar to $sanitizer->pageName() - I'm not sure if there are any advantages over that method. Included because it is one of the methods offered by EasySlugger.
      $slug = $sanitizer->slugger('Lorem Ipsum'); // Result: lorem-ipsum utf8Slugger($string, $options)
      Creates slugs from non-latin alphabets.
      $slug = $sanitizer->utf8Slugger('这个用汉语怎么说'); // Result: zhe-ge-yong-han-yu-zen-me-shuo seoSlugger($string, $options)
      Augments the string before turning it into a slug. The conversions are related to numbers, currencies, email addresses and other common symbols.
      $slug = $sanitizer->seoSlugger('The price is $5.99'); // Result: the-price-is-5-dollars-99-cents See the EasySlugger readme for some more examples.
      seoUtf8Slugger($string, $options)
      A combination of utf8Slugger() and seoSlugger().
      $slug = $sanitizer->seoUtf8Slugger('价钱是 $5.99'); // Result: jia-qian-shi-5-dollars-99-cents $options argument
      Each of the methods can take an $options array as a second argument.
      separator (string): the character that separates words in the slug. Default: - unique (bool): Determines whether a random suffix is added at the end of the slug. Default: false $slug = $sanitizer->utf8Slugger('这个用汉语怎么说', ['separator' => '_', 'unique' => true]); // Result: zhe_ge_yong_han_yu_zen_me_shuo_3ad66c4  
      https://github.com/Toutouwai/SanitizerEasySlugger
      https://modules.processwire.com/modules/sanitizer-easy-slugger/
    • By VeiJari
      Hello forum,
      This is really a weird one, because front end editing works in a earlier website we did to a customer. 
      When I check the source code for current website it does initiate front end edit: 
      <span id=pw-edit-1 class='pw-edit pw-edit-InputfieldPageTitle' data-name=title data-page=1021 data-lang='1017' style='position:relative'><span class=pw-edit-orig>Tekijät</span><span class=pw-edit-copy id=pw-editor-title-1021 style='display:none;-webkit-user-select:text;user- select:text;' contenteditable>Tekijät</span></span>  But when I double click nothing happens (yes I'm 100% sure I'm superuser and logged in)
      I also tried to apply the front end with other methods than:
      $page->edit('title'); But didn't work either.
      We are using jquery 2.2.4, so it should not be a problem.
      Is this a bug related to current master or something else?
      Someone else having this problem as well?
    • 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?
×
×
  • Create New...