1
1
<?php
2
2
/**
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/
4
5
*
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.
11
9
*/
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 );
13
12
function gppa_populate_checkboxes_as_choices ( $ choices , $ field , $ objects ) {
13
+
14
14
$ choices = array ();
15
15
$ templates = rgar ( $ field , 'gppa-choices-templates ' , array () );
16
- foreach ( $ objects as $ object ) {
17
- $ field_id = str_replace ( 'gf_field_ ' , '' , rgar ( $ templates , 'value ' ) );
18
16
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 ) {
19
26
foreach ( $ object as $ meta_key => $ meta_value ) {
20
- if ( absint ( $ meta_key ) === absint ( $ field_id ) ) {
27
+ if ( absint ( $ meta_key ) === absint ( $ source_field_id ) ) {
21
28
/**
22
29
* Some fields such as the multi-select store the selected values in one meta value.
23
30
*
@@ -28,19 +35,15 @@ function gppa_populate_checkboxes_as_choices( $choices, $field, $objects ) {
28
35
continue ;
29
36
}
30
37
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 );
43
40
}
41
+
42
+ foreach ( $ meta_value as $ value ) {
43
+ $ source_choice = $ source_field ->get_selected_choice ( $ value );
44
+ $ choices [] = $ source_choice ;
45
+ }
46
+
44
47
}
45
48
}
46
49
}
0 commit comments