1+ <?php
2+
3+ /**
4+ * Gravity Connect // Notion // Populate Select Field with Notion Database Options
5+ * https://gravitywiz.com/documentation/gravity-connect-notion/
6+ *
7+ * Populate a Select or Multi-Select field with the options from a Notion Database Select
8+ * or Multi-Select property.
9+ *
10+ * Instructions:
11+ *
12+ * 1. Change FORMID in the filter name to your form ID.
13+ * 2. Change the $field_id, $database_id, and $property_id variables to match your form and Notion database.
14+ * NOTE: the $database_id and $property_id can be found in the Javascript developer console in a GC Notion
15+ * feed settings AFTER the feed is connected to a database.
16+ */
17+
18+ add_filter ( 'gform_pre_render_FORMID ' , function ( $ form , $ ajax , $ field_values ) {
19+ $ field_id = 1 ; // Change this to the ID of the field you want to populate.
20+ $ database_id = 'DATABASE_ID ' ; // Change this to the ID of the Notion database which you want to populate values from.
21+ $ property_id = 'PROPERTY_ID ' ; // Change this to the ID of the property in the database which you want to populate values.
22+
23+ $ notion_account_id = \GC_Notion \Tokens::get_resource_service_account ( $ database_id );
24+ if ( empty ( $ notion_account_id ) ) {
25+ return $ form ;
26+ }
27+
28+ $ token = rgar ( \GC_Notion \Tokens::get_service_account_ids_to_tokens (), $ notion_account_id );
29+ if ( empty ( $ token ) ) {
30+ return $ form ;
31+ }
32+
33+ foreach ( $ form ['fields ' ] as $ field ) {
34+ if ( $ field ['id ' ] != $ field_id ) {
35+ continue ;
36+ }
37+
38+ try {
39+ $ api = new \GC_Notion \Notion_API_Client ( $ token );
40+ $ response = $ api ->get_database ( $ database_id );
41+
42+ foreach ( $ response ['properties ' ] as $ property ) {
43+ if ( rgar ( $ property , 'id ' ) !== $ property_id ) {
44+ continue ;
45+ }
46+
47+ $ type = rgar ( $ property , 'type ' );
48+ $ options = rgars ( $ property , $ type . '/options ' );
49+ $ choices = array_map ( function ( $ option ) {
50+ return array (
51+ 'value ' => $ option ['id ' ],
52+ 'text ' => $ option ['name ' ],
53+ );
54+ }, $ options );
55+
56+ $ field ['choices ' ] = $ choices ;
57+
58+ break ;
59+ }
60+ } catch ( \Exception $ e ) {
61+ // noop
62+ }
63+ }
64+
65+ return $ form ;
66+ }, 10 , 3 );
0 commit comments