Jump to content

Dynamic default value of a page field, based on the current user?


Michael van Laar
 Share

Recommended Posts

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.

Link to comment
Share on other sites

@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
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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...