Jump to content
PeterDK

kind of 'calculated field'?

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!

Share this post


Link to post
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 9

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...