11<?php
22/**
3- * See https://gravitywiz.com/documentation/how-do-i-install-a-snippet/ for details on how to install snippets like these.
3+ * Gravity Perks // Populate Anything // Populate Checkboxes (and Multi Selects) as Choices
4+ * https://gravitywiz.com/documentation/gravity-forms-populate-anything/
45 *
5- * The following snippet allows you to use a checkbox field as choices.
6- *
7- * This will use whatever property is selected in the "Value Template" for the choices.
8- *
9- * FORMID is the form that the field with dynamically populated choices is on
10- * FIELDID is the field ID of the field that you wish to modify the choices for
6+ * When populating data from a Checkbox or Multi Select field via the Gravity Forms Entry object type, all selected values
7+ * for the given field of each entry will be populated as a single choice. This snippet will split those values up into
8+ * separate choices.
119 */
12- add_filter ( 'gppa_input_choices_FORMID_FIELDID ' , 'gppa_populate_checkboxes_as_choices ' , 10 , 3 );
10+ // Update "123" to your form ID and "4" to your field ID.
11+ add_filter ( 'gppa_input_choices_123_4 ' , 'gppa_populate_checkboxes_as_choices ' , 10 , 3 );
1312function gppa_populate_checkboxes_as_choices ( $ choices , $ field , $ objects ) {
13+
1414 $ choices = array ();
1515 $ templates = rgar ( $ field , 'gppa-choices-templates ' , array () );
16- foreach ( $ objects as $ object ) {
17- $ field_id = str_replace ( 'gf_field_ ' , '' , rgar ( $ templates , 'value ' ) );
1816
17+ if ( empty ( $ objects ) ) {
18+ return $ choices ;
19+ }
20+
21+ $ source_form = GFAPI ::get_form ( $ objects [0 ]->form_id );
22+ $ source_field_id = str_replace ( 'gf_field_ ' , '' , rgar ( $ templates , 'value ' ) );
23+ $ source_field = GFAPI ::get_field ( $ source_form , $ source_field_id );
24+
25+ foreach ( $ objects as $ object ) {
1926 foreach ( $ object as $ meta_key => $ meta_value ) {
20- if ( absint ( $ meta_key ) === absint ( $ field_id ) ) {
27+ if ( absint ( $ meta_key ) === absint ( $ source_field_id ) ) {
2128 /**
2229 * Some fields such as the multi-select store the selected values in one meta value.
2330 *
@@ -28,19 +35,15 @@ function gppa_populate_checkboxes_as_choices( $choices, $field, $objects ) {
2835 continue ;
2936 }
3037
31- if ( is_array ( $ meta_value ) ) {
32- foreach ( $ meta_value as $ value ) {
33- $ choices [] = array (
34- 'value ' => $ value ,
35- 'text ' => $ value ,
36- );
37- }
38- } else {
39- $ choices [] = array (
40- 'value ' => $ meta_value ,
41- 'text ' => $ meta_value ,
42- );
38+ if ( ! is_array ( $ meta_value ) ) {
39+ $ meta_value = array ( $ meta_value );
4340 }
41+
42+ foreach ( $ meta_value as $ value ) {
43+ $ source_choice = $ source_field ->get_selected_choice ( $ value );
44+ $ choices [] = $ source_choice ;
45+ }
46+
4447 }
4548 }
4649 }
0 commit comments