Michael van Laar Posted October 25, 2016 Posted October 25, 2016 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.
Zeka Posted October 25, 2016 Posted October 25, 2016 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}"); 1
Michael van Laar Posted October 25, 2016 Author Posted October 25, 2016 Thanks @Zeka. It’s not exactly what I intended, but it gives me an idea how I could get what I want without much effort. Thanks a lot.
Robin S Posted October 26, 2016 Posted October 26, 2016 @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); }); 4
Michael van Laar Posted October 27, 2016 Author Posted October 27, 2016 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. 1
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now