Skip to content

Instantly share code, notes, and snippets.

@isotrope
Last active April 28, 2021 20:44
Show Gist options
  • Save isotrope/8fdd813e65eb5efb0255 to your computer and use it in GitHub Desktop.
Save isotrope/8fdd813e65eb5efb0255 to your computer and use it in GitHub Desktop.
Sum total of all fields with a class of XXXX and throw a validation error if the sum is == 0
<?php
//Don't forget to change the _1 in the hook to the ID of your form
add_filter('gform_validation_1', 'iso_min_sum_validate');
// Most code taken from http://www.gravityhelp.com/documentation/page/Using_the_Gravity_Forms_%22gform_validation%22_Hook
function iso_min_sum_validate($validation_result) {
// We'll base our loop on CSS class
$css_class_we_want = 'product-quantity';
$form = $validation_result["form"];
// Set up a counter for our field
$my_total = 0;
// Loop to see if we have a total greater than 0
foreach($form['fields'] as &$field){
// 5 - If the field does not have our designated CSS class, skip it
if(strpos($field['cssClass'], $css_class_we_want) === false)
continue;
$my_total = $my_total + intval(rgpost("input_{$field['id']}"));
}
if($my_total == 0) {
foreach($form['fields'] as &$field){
if(strpos($field['cssClass'], $css_class_we_want) === false)
continue;
$field['failed_validation'] = true;
$field['validation_message'] = __('Please select at least 1 product', 'pla');
}
$validation_result['is_valid'] = false;
$validation_result['form'] = $form;
}
return $validation_result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment