Update field based on date

Hi there!

I have created a collection of pages which include in their blueprint a hidden field called publishedStatus. It is automatically filled with predefined values after the page is updated, based on another field in the same blueprint called date.

As you can see in the hook below, if the date defined is older than 90 days, the publishedStatus is filled with ‘Old’, otherwise it is ‘New’, or upcoming, if the date is in the ‘future’.

'hooks' => [
  'page.update:after' => function ($page) {
    if ($page->intendedTemplate() == 'book') {
      $today = new DateTime(date('Y-m-d'));
      $publishedDate = new DateTime($page->date());
      $interval = $today->diff($publishedDate);
      if($publishedDate <= $today){
        if($interval->days <= 90){
          $page->update([
              'publishedStatus' => 'New'
          ]);
        } else{
          $page->update([
              'publishedStatus' => 'Old'
          ]);
        }
        } else {
          $page->update([
              'publishedStatus' => 'Upcoming'
          ]);
        }
      }
    }
  } 
]

Everything works fine for now. However, I’d like this publishedStatus field to update automatically without having to update the page in the panel. Is there a way to automate this?

Thank you for your help :slightly_smiling_face:

Why do you need this field in the first place?

Hi Sonja!

This field is used to filter the collection in other scripts and visually highlight when the page is old, new or upcoming. You can have a look at the current page here if this can help: Éditions Sarbacane.

I suggest you use the map() method to create a virtual field rather than storing this value in the content file to keep it dynamic.

I never used the map method. I’ll look into this. Thank you for your prompt reply :blush:

You can find example here on the forum, e.g. here: Custom Grouping Order