Last active
March 15, 2022 15:15
-
-
Save 89gsc/8fad874f20e695e3377b99a37a29c324 to your computer and use it in GitHub Desktop.
Gravity Forms - Set a radio selected button via PHP
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
add_filter('gform_pre_render', function($form) | |
{ | |
$user_consent_form = get_field('user_contact_preferences_form', 'option'); | |
if ($user_consent_form) { | |
if ($form['id'] === (int)$user_consent_form) { | |
// This should return an array if its set. | |
$user_consent_marketing = get_user_meta(get_current_user_id(), 'marketing_consent'); | |
if ($user_consent_marketing) { | |
// find out which field is "marketing_consent" | |
foreach ($form['fields'] as &$field) { | |
if ($field['adminLabel'] === 'marketing_consent' | |
&& $field['type'] === 'radio') { | |
if (is_array($field['choices'])) { | |
$replaced_choices = []; | |
foreach ($field['choices'] as &$choice) { | |
if ($choice['value'] === $user_consent_marketing[0]) { | |
$choice['isSelected'] = true; | |
} | |
$replaced_choices[] = $choice; | |
} | |
$field['choices'] = $replaced_choices; | |
} | |
} | |
} | |
} | |
} | |
} | |
return $form; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should be noted that in the second foreach for choices if you don't use a $replacement_choices array and resave this against the $field['choices'] it wont end up being set in the final return.... took me too long to realise this.