Posted on by

Custom Participant Log Sums

Each log defined in the Participant Log add-on has what’s known as a “summary” that is a number that is used to present an important value drawn from a record’s log entries. This value is calculated and saved to the record so that it can be used in other ways, such as filtering or sorting based on the calculated summary value.

The default summary value is simply the number of entries, but it’s also possible to show a summary based on log field values. For example, the total number of hours logged in a work log.

In some cases, it is desirable to show a summary value based on a more complex calculation, such as an average or calculations based on several values from the log.

Setting Up a Custom Log Summary Calculation

In order to customize how the summary is calculated, you need to use a bit of custom code that replaces the built-in calculation. This is done using a filter that replaces the normal value with your custom calculation.

In this tutorial, I include a plugin that can serve as the basic framework for implementing a custom calculation. I am using the example of a work log for volunteers, where each log entry is a day that the volunteer put in some hours. The summary we want to see is the average number of hours the volunteer put in per day that they volunteered.

How the Code Works

The plugin works by attaching a function to the filter that is applied to the normal sum value. This filter is pdblog-{$log_name}_sum where {$log_name} is the name of the log. In this case, the name of the log is work_log and so the filter we will be using is pdblog-work_log_sum.

The filter provdes two values: the normal calculated sum and an array of all the record’s log entry data. Each element in the array is an object containing the values of the entry.

This filter is called whenever the summary is displayed.

In our plugin, we iterate over the array of entries and collect the “hours” values and sum them together. To complete the calculation, we average using the number of entries.

Customizing the Plugin

To use this plugin in your own setup, you will first need to set the $logname property (line 13) to the name of your log.

Next, you will need to change the pdb_custom_log_sum::calculate() method to perform the calculation you want. The method should return the result of the calculation as a number. The first bit of code in that method will be needed so that you have a way of dealing with a record that has no log entries.

Wondering how to get the code? Check this: How to Install a WordPress Plugin from a Gist

Leave a Reply

Your email address will not be published. Required fields are marked *

Leave a Reply

Your email address will not be published. Required fields are marked *