I am using Gravity forms with one Radio Button and one Checkboxes field they both have same choices. What I need is when my user chooses a choice on Radio Button, this choice is automatically pre-selected on the Checkboxes field. He doesn't have to select it again.
I saw I have to use some filter, for example, the one below, but I cannot succeed to customize it in order to do what I need.
If someone could help me he will save my life.
<?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
Glad that worked for you, Jean.
For other folks needing to do this, we've written a full walkthrough on the process along with an easy-to-follow use-case.
How to Check Checkboxes (and Other Choice-based Fields) Conditionally
Here's a quick crash course:
Create a Mapping Form
Create a form that will be used to keep track of which checkboxes should be checked when a given option (in another field) is selected.
Submit Form Entries
Now you'll go through and do some data entry. Select the trigger option and then select each checkbox that should be checked for that option.
Duplicate the Mapping Form
Next, you'll create a new form based on your mapping form. This is the form that your users would actually interact with. The mapping form is just for you.
Map Your Fields
Lastly, use Populate Anything to dynamically checked (i.e. populate the value) of your Checkbox field based on the option selected and the checkboxes checked for that option from your mapping form.