Gravity Forms – Checkbox Dynamic Population
The gform_pre_render filter is executed before the form is displayed and can be used to manipulate the?Form Object?prior to rendering the form.?It is generally used to dynamically populate form controls before the form is rendered.
Checkbox controls are special, in that they are treated as multi-input fields (similar to “Name” and “Address” fields). Besides the “choices” property which they share with “select”, “multi-select” and “radio” controls, they also have an “inputs” property. Please check the Field Object?documentation page for more details.
Because of this,?dynamic population for checkbox controls is somewhat different compared to the other multi-choice field controls.
The following approach can be used for checkboxes: on “gform_pre_render” use RGFormsModel::get_form_meta() method to fetch the form from database, then populate the form controls as required, and then the form is saved back to the database using RGFormsModel::update_form_meta(). This behaviour can be controlled using a boolean constant, as shown below:
// When true, the form will be saved to DB after dynamic population
define('WPB_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', 'wpb_populate_checkbox');
add_filter('gform_admin_pre_render_7', 'wpb_populate_checkbox');
function wpb_populate_checkbox($form) {
if (WPB_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 (WPB_SAVE_FORM_ON_PRE_RENDER)
RGFormsModel::update_form_meta($form['id'], $the_form);
return $the_form;
}
Using this approach you can view the checkbox values in the entry list as well as change the entry, by updating the submitted checkbox values.