Skip to content

Instantly share code, notes, and snippets.

@89gsc
Last active March 15, 2022 15:15
Show Gist options
  • Save 89gsc/8fad874f20e695e3377b99a37a29c324 to your computer and use it in GitHub Desktop.
Save 89gsc/8fad874f20e695e3377b99a37a29c324 to your computer and use it in GitHub Desktop.
Gravity Forms - Set a radio selected button via PHP
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;
});
@89gsc
Copy link
Author

89gsc commented Mar 15, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment