Setting a field value from PHP [RESOLVED]

Hi.
Im using some php code to do some custom validation. If it fails I need to set a field’s value. How do I do this from my php function? Ive tried this but t doesnt work (Ive set the relevant field to “Allow field to be populated dynamically” with the param name of dob_problem):

add_filter( 'gform_field_value_dob_problem', 'my_custom_population_function' );
		function my_custom_population_function( $value ) {
			return 'boom!';
		}

Thanks

The problem with gform_field_value is it loads when all forms and fields are loaded. So to make it work on a specific field and form you need it to look something more like this:

add_filter( 'gform_field_value', 'my_custom_function001', 10, 5 );
function my_custom_function001( $input, $field, $value ){
 if( $field->formId == 1 && $field->id == 2 ){
	 $value = 'Boom';
	 return $value;
 }
 return $value;
 }

Thanks Parkbum.

Im checking to see if user is less than 18. If they are then I want to set the value of a field (with the param name of dob_problem). Im obviously not doing something right:

// check is user is less than 18
add_filter( 'gform_field_validation_18_118', function ( $result, $value, $form, $field ) {

	$dob = rgpost('input_118');
	
	$bday = $dob[0];
	$bmon = $dob[1];
	$byr = $dob[2];
	//die($bday . $bmon . $byr);
	
	
	$stampBirth = mktime(0, 0, 0, $bmon, $bday, $byr);
	$today['day']   = date('d');
	$today['month'] = date('m');
	$today['year']  = date('Y') - 18;
	$stampToday = mktime(0, 0, 0, $today['month'], $today['day'], $today['year']);

	
	if ($stampBirth > $stampToday) {
		$result['is_valid'] = false;
        $result['message'] = "YOU ARE LESS THAN 18. FINNISH THIS BIT";
		
		add_filter( 'gform_field_value_dob_problem', 'my_custom_function001', 10, 5 );
		function my_custom_function001( $input, $field, $value ){
		 if( $field->formId == 18 && $field->id == 124 ){
			 $value = 'Boom';
			 return $value;
		 }
		 return $value;
		 }

		
	}


    return $result;
}, 10, 4 );

No problem. I haven’t spent much time with the gform_field_validation hook. I usually do my complex validation through JavaScript.

Side thought to maybe help you out. To checking your work, you should put in a few console logs to see if things are coming through properly:

echo'<script>console.log'. print_r($stampBirth) .'</script>';
echo'<script>console.log'. print_r($today) .'</script>';
echo'<script>console.log'. print_r($stampToday) .'</script>';

1 Like

gform_field_value runs when the form is loaded, not any time afterward. If you are trying to set a field value when performing your age validation, you can populate the field in the $_POST directly:

if ($stampBirth > $stampToday) {
	$result['is_valid'] = false;
	$result['message'] = "YOU ARE LESS THAN 18. FINNISH THIS BIT";
	$_POST['input_124'] = 'Boom'; // or whatever actual value
}
2 Likes

Fantastic. That works! Many thanks.

1 Like