Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstrates how to pre-populate checkbox fields when using the Gravity Forms plugin for WordPress
<?php
# Make sure to replace {id} with your form's id
add_filter( 'gform_pre_render_{id}', 'my_populate_checkbox' );
function my_populate_checkbox( $form ) {
/**
* Loop through form fields
*
* Note we are using the `$field` array as a direct reference using `&`.
* This means that changing its value will within the loop will
* change the corresponding `$form` array item
*/
foreach( $form['fields'] as &$field ) {
# Make sure to change `1` to the ID of the checkbox field that you want to pre-populate
if( 1 === $field->id ) {
/**
* Loop through the choices for this checkbox
*
* Note again that we are passing `$choice` by reference in order to change the
* corresponding array item within the `$field` array
*/
foreach( $field->choices as &$choice ) {
/**
* If this choice has a value of 'red' or 'blue', then make sure the checkbox is pre-checked
* by setting the `isSelected` parameter to `true`
*/
if( 'red' === $choice['value'] || 'blue' === $choice['value'] ) {
$choice['isSelected'] = true;
}
} # end foreach: $field->choices
} # end if: $field->id equals 1
} # end foreach: $form['fields']
# return the altered `$form` array to Gravity Forms
return $form;
} # end: my_populate_checkbox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.