Jump to content

A hook to auto-populate fields


nuel
 Share

Recommended Posts

Hi

I'm working with PW for some time now, but – please don't laugh – never used hooks.

I have 200 – 300 subpages with the template 'artist', the title of each page represents the full name, sometimes John Doe, sometimes John Emmet Brown Doe. I want to auto-populate the field 'artist_last_name' with the word that is most likely the last name, the last word of the page title. If there are more names, it can be changed manually. I need this for easier and quicker alphabetical sorting.

What I put together is this, in ready.php. Doesn't work. Again, I'm new to hooks..

<?php
    $wire->addHookBefore('Pages::saved', function(HookEvent $event) {
    $p = $event->arguments('page');
    if($p->template != 'artist') return;
    if($p->artist_last_name) return;
    $ln = end(explode(' ', $p->title));
    $p->set('artist_last_name',$ln);
    });
?>

In the best case this would be done once globally without having to open and save every page. But new pages should populate the field on page save.

Thanks for your help, I think it's easy, I just need a push..

Nuél

Link to comment
Share on other sites

What about this? (not tested)
 

$pages->addHookAfter('saveReady', function($event) {
    $p = $event->arguments('page');
    if($p->template != 'artist') return;
    if($p->artist_last_name) return;
    $ln = explode(' ', $p->title);
	$lastname = array_pop($ln);
    $p->set('artist_last_name',$lastname);
})
Link to comment
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
 Share

×
×
  • Create New...