Jump to content

Recommended Posts

Posted

Is it possible to prepopulate a page field with a dynamic value, using a selector or something similar, instead of a static default value?

I’m just curious. It’s not super important, as you can see below. It would just add a little more convenience.

 

My use case:

In a blog project I have pages with the template “author” which are used to store information about the blog’s authors. Some of these authors have ProcessWire user accounts – but not all of them. This separation is intended because it doesn’t make sense to create a user account for a one-time guest author who shouldn’t enter his article into the CMS by himself. If an author has a ProcessWire user account, this connection can be set via a page field on the author page.

In the “article” template there is a page field to choose the blog article’s author from. Since this is a required field, I can add static default value to its configuration. But what I’d like to provide for convenience: If a user creates a new blog article, the author field should be prepopulated with “his” author page, i. e. the author page which matches something like “template=author, corresponding_user={$user->id}”. This is not achievable with the static default value configuration option of the page field.

Posted

Hi @Michael van Laar

For selectable pages in your page field, try the "Custom PHP code to find selectable pages" option...

return $pages->find("parent=/blog/, author={$this->user->name}");
  • Like 1
Posted

@Michael van Laar, you could use a hook to set the value of the Page field after a new article page is added. In /site/ready.php:

$this->pages->addHookAfter('added', function($event) {
    $page = $event->arguments('page');
    if($page->template->name != 'article') return;
    // your logic here to find the right author ID
    $page->setAndSave('author', $my_author_id);
});

 

  • Like 4
Posted

Wow, thanks @Robin S. That’s exactly what I was searching for.

I haven’t learned much about hooks yet, simply because there was no need by now. I thought I have to write a module to achieve this. But putting this in the ready.php works like a charm and is super easy to set up.

  • Like 1

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.
×
×
  • Create New...