Skip to content

Instantly share code, notes, and snippets.

@webaware
Last active May 10, 2019 21:25
Show Gist options
  • Save webaware/5349924 to your computer and use it in GitHub Desktop.
Save webaware/5349924 to your computer and use it in GitHub Desktop.
Example of using the gform_pre_render filter hook to perform calculations, returning results in dynamically populated fields. See documentation links for more info. http://www.gravityhelp.com/documentation/page/Gform_pre_render http://www.gravityhelp.com/documentation/page/Using_Dynamic_Population
<?php
/**
* excerpt from compound classroom field, for example purposes only
* the real class is over 700 lines
*/
class OlpcGfClassroomField {
/**
* hook into Gravity Forms
*/
public function __construct() {
add_filter('gform_pre_render', array($this, 'gformPreRender'));
}
/**
* count the students and training participants in the classroom fields
* @param array $form
* @return array
*/
public function gformPreRender($form) {
$students = 0;
$participants = 0;
$studentsField = false;
$participantsField = false;
// search fields to find classroom fields, and our dynamically populated fields
foreach ($form['fields'] as $field) {
// check for our custom field type
if ($field['type'] == OLPCGF_FIELD_CLASSROOM) {
$values = $this->getPost($field['id']);
if (is_numeric($values['students']) && $values['students'] > 0) {
$students += $values['students'];
}
if ($values['trainingparticipant']) {
$participants++;
}
}
// check for dynamically populated fields with our special keys
elseif ($field['inputName'] == 'olpcgf_total_class_students') {
$studentsField = $field;
}
elseif ($field['inputName'] == 'olpcgf_total_class_training') {
$participantsField = $field;
}
}
// set total students field
if ($studentsField) {
$_POST['input_' . $studentsField['id']] = $students;
}
// set total participant laptops field
if ($participantsField) {
$_POST['input_' . $participantsField['id']] = $participants;
}
return $form;
}
/**
* get input values for compound field
* @param integer $field_id
* @return array
*/
protected static function getPost($field_id) {
$values = rgpost('olpcgf_' . $field_id);
if (is_array($values)) {
$values = array (
'fname' => $values[1],
'lname' => $values[2],
'email' => $values[3],
'mobile' => $values[4],
'role' => isset($values[5]) ? $values[5] : array(),
'level' => isset($values[6]) ? $values[6] : array(),
'students' => GFCommon::to_number($values[7]),
// checkbox, may not be present:
'trainingparticipant' => isset($values[8]) ? $values[8] : '',
);
}
else {
$values = false;
}
return $values;
}
}
// create an instance of the class, which hooks into Gravity Forms
// (references to the class keep it alive, no need to store in a variable)
new OlpcGfClassroomField();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment