Jump to content

kind of 'calculated field'?


PeterDK
 Share

Recommended Posts

I have a few simple statistic fields per user (see current site)

Every user has these:

  Member for X Years (count of 'membership groups')

  Total distance ridden (sum of distance field of all page with template 'rides' where the current user is 'participant')

Then per year => distance and totalrides and 'avg distance per ride'.

All very simple if done only one time but, we have 300 riders and currently 2000 rides AND i would like to sort on those fields!

For instance a small table sorted on the rider (user) with the most miles ridden.

Now the question:

Is there a field type that is 'php code' executed when someone edits 'rides'. The result of the code could be stored in the field (and sorted, queried).

Thanks a million!

Link to comment
Share on other sites

When I need a calculated field that will be used for sorting, I like to add a hidden (or regular, doesn't matter) field to the template to store the calculated value. The value gets automatically calculated on page save. A hook like this in your /site/templates/admin.php can do the work for you:

$pages->addHook('saveReady', function($event) {
  $pages = $event->object; 
  $page = $event->arguments(0); 
  if($page->template == 'rider') {
    $miles = 0;
    foreach($page->rides as $ride) {
      $miles += $ride->miles;
    } 
    $page->miles_ridden = $miles;
  }
}); 

Then when it comes to sorting, you just sort on your calculated field: miles_ridden. If you are adding this to an existing PW installation, then you'd need to establish the initial values for each rider's miles_ridden. This could be done with a quick bootstrapped script:

/setup-riders.php

<pre><?php
include("./index.php"); 
foreach(wire("pages")->find("template=rider") as $rider) {
  $rider->save();
  echo "$rider->name: $rider->miles_ridden miles ridden\n";
}

Then you'd just load domain.com/setup-riders.php in your web browser, and then delete the file when done. 

  • Like 10
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...