Created
March 23, 2021 17:31
-
-
Save tannermann/3b4f989731562f3e32e2127d2a18a368 to your computer and use it in GitHub Desktop.
Gravity Forms Checkbox Dynamic Population with User Registration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Save user sport interests when activating user based on their original submission | |
add_action( 'gform_activate_user', 'after_user_activate', 10, 3 ); | |
function after_user_activate( $user_id, $user_data, $signup_meta ) { | |
$sports_string = get_user_meta($user_id, 'sports_interested_in', true); | |
$sports_slug_array = explode(', ', $sports_string); | |
$sports_array = array(); | |
foreach($sports_slug_array as $sports_slug) { | |
$sport_type_term_object = get_term_by('slug', $sports_slug, 'sport_type'); | |
$term_id = $sport_type_term_object->term_id; | |
$sports_array[] = $term_id; | |
} | |
// Sports checkbox field key | |
$field_key = "field_60483583b8d1a"; | |
update_field( $field_key, $sports_array, 'user_' . $user_id ); | |
} | |
add_filter( 'gform_pre_render_2', 'pk_populate_sport_type_choices' ); | |
add_filter( 'gform_pre_validation_2', 'pk_populate_sport_type_choices' ); | |
add_filter( 'gform_pre_submission_filter_2', 'pk_populate_sport_type_choices' ); | |
add_filter( 'gform_admin_pre_render_2', 'pk_populate_sport_type_choices' ); | |
function pk_populate_sport_type_choices( $form ) { | |
$sport_type_args = [ | |
'taxonomy' => 'sport_type', | |
'order' => 'ASC', | |
'hide_empty' => false, | |
]; | |
$sport_types = get_terms( $sport_type_args ); | |
foreach( $form['fields'] as &$field ) { | |
$field_id = 8; | |
if ( $field->id != $field_id ) { | |
continue; | |
} | |
$input_id = 1; | |
$choices = []; | |
$inputs = []; | |
foreach( $sport_types as $sport_type ) { | |
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs) | |
if ( $input_id % 10 == 0 ) { | |
$input_id++; | |
} | |
$choices[] = [ 'text' => $sport_type->name, 'value' => $sport_type->slug ]; | |
$inputs[] = array( 'label' => $sport_type->name, 'id' => "{$field_id}.{$input_id}" ); | |
$input_id++; | |
} | |
$field->choices = $choices; | |
$field->inputs = $inputs; | |
} | |
return $form; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment