Copy Values for Conditionally Hidden Fields

By default, Gravity Forms does not capture values for fields hidden by conditional logic. Use this snippet to “copy” values to hidden fields on submission.

Code

Filename: gpcc-copy-to-conditionally-hidden-fields.php

<?php
/**
 * Gravity Perks // Copy Cat // Copy Values for Conditionally Hidden Fields
 * https://gravitywiz.com/documentation/gravity-forms-copy-cat/
 *
 * By default, Gravity Forms does not capture values for fields hidden by conditional logic. Use this snippet to "copy"
 * values to hidden fields on submission.
 */
add_action( 'gform_entry_post_save', function( $entry, $form ) {

	if ( ! is_callable( 'gp_copy_cat' ) ) {
		return $entry;
	}

	$orig_entry = $entry;
	$triggers   = gp_copy_cat()->get_copy_cat_fields( $form );

	foreach ( $triggers as $trigger_field_id => $targets ) {

		$is_trigger_hidden = GFFormsModel::is_field_hidden( $form, GFAPI::get_field( $form, $trigger_field_id ), array(), $entry );
		if ( $is_trigger_hidden ) {
			continue;
		}

		foreach ( $targets as $target ) {

			$is_target_hidden = GFFormsModel::is_field_hidden( $form, GFAPI::get_field( $form, $target['target'] ), array(), $entry );
			if ( ! $is_target_hidden ) {
				continue;
			}

			$source_field  = GFAPI::get_field( $form, $target['source'] );
			$source_values = $source_field->get_value_submission( array() );

			if ( is_array( $source_values ) ) {
				foreach ( $source_values as $input_id => $source_value ) {
					$target_input_id           = str_replace( "{$source_field->id}.", "{$target['target']}.", $input_id );
					$entry[ $target_input_id ] = $source_value;
				}
			} else {
				$entry[ $target['target'] ] = $source_values;
			}
		}
	}

	if ( $orig_entry !== $entry ) {
		GFAPI::update_entry( $entry );
	}

	return $entry;
}, 9, 2 );

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.