Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active February 28, 2022 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnau/9bc6bfa1046e0f2927d25a10ce185ed6 to your computer and use it in GitHub Desktop.
Save xnau/9bc6bfa1046e0f2927d25a10ce185ed6 to your computer and use it in GitHub Desktop.
Shows how to set up a custom calculation for a Participants Database calculated field
<?php
/**
* Plugin Name: PDB Custom Calculated Field
* Description: demonstrates how to implement a custom calculation for a calculated field
*/
add_filter( 'pdb-calculated_field_calc_value', 'pdb_calculate_value', 10, 3 );
/**
* supplies the calculated value
*
* @param bool $result
* @param array $replacement_data values for the fields named in the calculation template
* @param \PDb_Field_Item $field the current field
* @return mixed bool false to use built-in calculation or the result of the calculation
*/
function pdb_calculate_value( $result, $replacement_data, $field )
{
/* this is the field that we will be calculating the value for
*
* this must be the name of a Numeric Calculation or Date Caclculation field
*
*/
$field_name = 'totals';
if ( $field->name() === $field_name ) {
$record_data = Participants_Db::get_participant( $field->record_id );
// shows a way to convert a text value to a number
$value_1 = $record_data['automobiles'] === 'local' ? 1 : 2;
// this value is set to 0 if it is empty to make sure the value is a number
$value_2 = empty( $replacement_data['distance'] ) ? 0 : $record_data['distance'];
$result = $value_1 * $value_2;
}
return $result;
}
@xnau
Copy link
Author

xnau commented Feb 28, 2022

If you are using this to calculate a value based on other calculated field results, those other fields must be calculated first. You can set that up by changing the order of the fields on the Manage Database Fields page. Fields are calculated from top to bottom sequentially.

The result of the prior calculations will be in $replacement_data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment