Noel Boss

A hook to prefill PageTable fields with children on edit

Recommended Posts

Posted (edited)

I use a PageTable field to make edits to children of pages more intuitive

To register the hooks, insert the following Snippet inside your init function in your module (or add it to your init.php file):

/**
 * Initialize the module.
 *
 * ProcessWire calls this when the module is loaded. For 'autoload' modules, this will be called
 * when ProcessWire's API is ready. As a result, this is a good place to attach hooks.
 */
public function init()
{
	// Prefill pageTable field
	$this->wire()->addHookBefore('InputfieldPageTable::render', $this, 'addChildrenToPageTableFieldsHook');
	$this->wire()->addHookBefore('InputfieldPageTableAjax::checkAjax', $this, 'addChildrenToPageTableFieldsHook');
}

Then, add this hook method:

/**
 * Fill pagetable fields with children before editing….
 *
 * @param HookEvent $event
 */
public function addChildrenToPageTableFieldsHook(HookEvent $event)
{
	$field = $event->object;

	// on ajax, the first hook has no fieldname
	if (!$field->name) {
		return;
	}
	
	// get the edited backend page
	$editID = $this->wire('input')->get->int('id');
	if (!$editID && $this->wire('process') instanceof WirePageEditor) {
		$editID = $this->wire('process')->getPage()->id;
	}
	$page = wire('pages')->get($editID);
	
	// disable output formating – without this, the ajax request will not populate the field
	$page->of(false);
	
	// you could also insert a check to only do this with sepcific field names…
	// $page->set($field->name, $page->children('template=DesiredTemplate')); // just specific templates
	$page->set($field->name, $page->children);
}

Now whenever there is a page-table field on your page, it gets populated with the children

Edited by Noel Boss
Using $page->set() instead of ->add() removes "orphant message"
  • Like 5

Share this post


Link to post
Share on other sites

could you please mark this as [tutorial] or could an admin move it to the tutorials board? thx

  • Like 2

Share this post


Link to post
Share on other sites

@bernhard I felt my post is not qualified for a tutorial with »step-by-step instructions on how to do things in ProcessWire« – and since the description for API & Templates contains »answers and support on the API and template development« I thought it would better fit in there. I was actually looking for a hooks / snippet / recipe section in the forum – but that does not exists. I know, there is https://processwire-recipes.com but it just feels to cumbersome to add one 😉

  • Like 1

Share this post


Link to post
Share on other sites

OK i understand 🙂 I just didn't get that it was a snippet and "wasted" time to read your post and try to help where actually no problem existed and thought you might save others from that by naming it more obviously..

  • Like 1

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 masslevel
      Hello!
      I apologize in advance if I missed something on the forums. I'm not yet that experienced with hooks and already tried a lot. Maybe someone else has an idea or could give me a hint in the right direction.
      In my ready.php file I'm creating a random generated URL slug on Pages::setupNew for a specific template. When creating a page and I type in the default language title and leave the other languages blank, the slug gets appended to the page names because the pages have the same url/slug/title but in different trees ( ex. /myarticle-myslug/ and /en/myarticle-myslug/ ) When creating a page and I enter a title for each language, the slug gets only applied to the default language and I get an error that the name for the default language already exists and it was changed to /myarticle-myslug/. The other language gets the page name /en/my-article/ applied. Additionally I noticed that the settings from Module -> Page Name (InputfieldPageName) are not applied when creating the page name using the code below. So non-ascii characters get stripped instead of sanitized Here is a simplified code snippet that I have in the ready.php file:
      wire()->addHookBefore('Pages::setupNew', function($event) { $page = $event->arguments('page'); if ($page->template->name == 'news-article') { $page->name = $page->title . '-myslug'; } }); I've read this topic and if this still applies, LanguageSupportPageNames isn't used on Pages::setupNew.  Especially the post by @Soma looks interesting but I'm not sure how to apply it.
      Thank you very much in advance.
    • By dragan
      $this->addHookBefore('InputfieldTextarea::render', function($event) { $field = $event->object; if($field->name == 'body_offer') { $del = ''; foreach($this->wire->pages->get(11229)->textblocks as $item) { $field->entityEncodeText = false; $body = str_replace(PHP_EOL, '', $item->body); $body = addslashes($body); $title = $item->title; $field->description .= $del . "<a href=\"#\" class=\"ckesnippet\" data-snippet=\"$body\">$title</a>"; $del = ' | '; } } $js = wire('config')->urls->templates . 'scripts/ckesnippets.js'; $event->return = str_replace("</html>", "\n<script type='text/javascript' src='$js'></script>\n</html>", $event->return); }); I'm trying to add custom text-blocks from repeater fields into CKEditor. I've stolen the whole idea (and code) from @bernhard

      Problem is: The links are actually being rendered, but the Javascript is not loaded, i.e. the $event->return line doesn't seem to work. If I inspect the HTML, my additional script-tag is nowhere to be seen. I don't get any errors either. Running latest PW dev + PHP 7.1.19.
    • By Sten
      Hello,

      I still did not solve my problem about Hebrew letters. In fact, it is ok for Russian for example to have a transliteration of characters (one to one) but in languages like Hebrew, Arabic, it is better to slugify with phonetic like here :
      use EasySlugger\Utf8Slugger; $slug = Utf8Slugger::slugify('日本語'); // slug = ri-ben-yu $slug = Utf8Slugger::slugify('العَرَبِيةُ‎‎'); // slug = alrbyt $slug = Utf8Slugger::slugify('עברית'); // slug = bryt So I am planning to insert https://github.com/javiereguiluz/EasySlugger
      Should I create a module or just add a hook ?
       
      I am a PW newbie.
      Thanks for your help
       
    • By Andreas Augustin
      hello,
      I want to build a custom validator on my multilang site.
      I added following hook, but I get only the default language value. How can I access the values of the other languages?
       
       
      public function init() { $this->addHookAfter("InputfieldTextarea::processInput", $this, "validateShortlinks"); } public function validateShortlinks($event) { $field = $event->object; $text = $field->value; // only the default language, how can I get the other languages? }  
    • By benbyf
      Hello, having trouble getting PW to save my user or field in cron hook.
      It seems to report the same field info each time unchanged. It should be counting down in seconds.
      public function init() { // set to every30Seconds in settings $this->defaultInterval = $this->cron_check; // add hooks to CRON $this->addHookAfter("LazyCron::{$this->defaultInterval}", $this, 'checkUserSubscription'); } public function ___checkUserSubscription(HookEvent $e){ // seconds since last lazycron $seconds = $e->arguments[0]; $log = wire('log'); $field = $this->exclusiveRole; // users with specific role and field $users = $this->users->find("roles=$field"); foreach ($users as $user) { // get stored time $currentTime = $user->get($this->fieldName); // if time not null if($currentTime){ // evalute stored time minus time past $resultTime = intval($currentTime) - intval($seconds); $log->message("result ".$resultTime); // save user page $user->set($this->fieldName, $resultTime); $this->users->save($user); } } }