Last active
December 8, 2022 11:37
-
-
Save eugenoprea/4700209 to your computer and use it in GitHub Desktop.
Gravity Forms - Checkbox Dynamic Population
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
// When true, the form will be saved to DB after dynamic population | |
define('EO_SAVE_FORM_ON_PRE_RENDER', true); | |
// Adds a filter to form id 7. Replace 26 with your actual form id | |
add_filter('gform_pre_render_7', 'eo_populate_checkbox'); | |
add_filter('gform_admin_pre_render_7', 'eo_populate_checkbox'); | |
function eo_populate_checkbox($form) { | |
if (EO_SAVE_FORM_ON_PRE_RENDER) | |
$the_form = RGFormsModel::get_form_meta($form['id']); | |
else | |
$the_form = &$form; | |
// Creating choices | |
$choices = array( | |
array('text' => 'Choice 1', 'value' => 'choice1'), | |
array('text' => 'Choice 2', 'value' => 'choice2'), | |
array('text' => 'Choice 3', 'value' => 'choice3'), | |
); | |
$inputs = array( | |
array('label' => 'Choice 1', 'id' => '2.1'), // replace 2 in 2.1 with your field id | |
array('label' => 'Choice 2', 'id' => '2.2'), // replace 2 in 2.2 with your field id | |
array('label' => 'Choice 3', 'id' => '2.3'), // replace 2 in 2.3 with your field id | |
); | |
// Adding items to field id 2. Replace 2 with your actual field id. | |
// You can get the field id by looking at the input name in the markup. | |
foreach ($the_form['fields'] as &$field) { | |
// replace 2 with your checkbox field id | |
if ($field['id'] == 2) { | |
$field['choices'] = $choices; | |
$field['inputs'] = $inputs; | |
} | |
} | |
// Save form to database, if constant is set to true | |
if (EO_SAVE_FORM_ON_PRE_RENDER) | |
RGFormsModel::update_form_meta($form['id'], $the_form); | |
return $the_form; | |
} |
Hi! Thanks for posting this - it's the perfect guide to help me figure out a gravity forms problem! If you have the time I have a question. How would you pre-select a checkbox based on the page the form is on? This is the last piece of my GF puzzle -- if you have any ideas around this I would be grateful for your help.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the form is AJAX, I think the custom additions are lost in case of validation errors. That's what we're seeing. Experiences? Perhaps this needs to be done at JS level instead https://www.gravityhelp.com/forums/topic/dynamically-populating-checkboxes
EDIT yes you need 4 filters, see https://www.gravityhelp.com/documentation/article/gform_pre_render/#example-2