I have a form set up with gravity forms that sells courses (courses are set up as a custom post) that uses the user registration and stripe payment add-ons.
If the user is not logged in then they are presented with user registration fields to create an account along with dynamic course cost total field.
Gravity form entries are associated to a course which gives a course candidiates list.
I have a couple of functions for validating the form to check if there is still an available place on the course when the form is submitted (this is to protect overselling the course if 2 or more people are on the course form page at the same time). When the course has 1 entry left the validation seems to fail - the user is not created but the stripe payment goes through and a form entry appears.
My Validation function:
add_filter( 'gform_validation', 'custom_validation' );
function custom_validation( $validation_result ) {
$form = $validation_result['form'];
// Return without changes if form id is not 1.
if ( 1 != $form['id'] ) {
return $validation_result;
}
// get course id from hidden input field 9
$sub_course_id = rgpost( 'input_9' );
// get the course availability from ACF field
$sub_course_capacity = get_field('availability', $sub_course_id);
$sub_course_availability = ($sub_course_capacity - calc_availability($sub_course_id) );
//Take the total course entries away from init capacity
if($sub_course_availability < 1){
// set the form validation to false
$validation_result['is_valid'] = false;
//finding Field with ID of 6 and marking it as failed validation
foreach( $form['fields'] as &$field ) {
//FIELD 6 IS THE "TOTAL" FIELD TO SHOW VALIDATION ERROR
if ( $field->id == '6' ) {
$field->failed_validation = true;
$field->validation_message = 'Sorry this course is now sold out!';
break;
}
}
}
//Assign modified $form object back to the validation result
$validation_result['form'] = $form;
return $validation_result;
}
Availability function:
function calc_availability($course_id){
$search_criteria = array(
'status' => 'active',
'field_filters' => array(
array(
'key' => '9', //this is the field id
'value' => $course_id
)
)
);
$entry_count = GFAPI::count_entries(1, $search_criteria); // 1 is your form id
return $entry_count;
}
I have printed various things to the logs from the main validation function and looking at the sub_course_availability it correctly comes through with a value of 1, but then appears again with a value of 0 which looks like it is throwing my validation off - the value of 0 would be the correct value after the form submission but not at the validation stage?
Am I missing something when using the GFAPI::count_entries hook to mitigate draft entries? Although I can't see anything in the docs regarding this.
Any help with this would be greatly appreciated. Thanks
