Skip to content

Commit 0e45fe3

Browse files
committed
gcn-populate-select.php: Added snippet to dynamically populate Select and Multi-Select fields from the options in a Select or Multi-Select field in a Notion database.
1 parent 6600b88 commit 0e45fe3

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

gc-notion/gcn-populate-select.php

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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+
*
14+
* 2. Change the $field_id, $database_id, and $property_id variables to match your form and Notion database.
15+
*
16+
* > 💡 The $database_id and $property_id can be found in the Javascript developer console in a GC Notion
17+
* > feed settings AFTER the feed is connected to a database.
18+
*/
19+
20+
add_filter( 'gform_pre_render_FORMID', function( $form, $ajax, $field_values ) {
21+
$field_id = 1; // Change this to the ID of the field you want to populate.
22+
$database_id = 'DATABASE_ID'; // Change this to the ID of the Notion database which you want to populate values from.
23+
$property_id = 'PROPERTY_ID'; // Change this to the ID of the property in the database which you want to populate values.
24+
25+
$notion_account_id = \GC_Notion\Tokens::get_resource_service_account( $database_id );
26+
if ( empty( $notion_account_id ) ) {
27+
return $form;
28+
}
29+
30+
$token = rgar( \GC_Notion\Tokens::get_service_account_ids_to_tokens(), $notion_account_id );
31+
if ( empty( $token ) ) {
32+
return $form;
33+
}
34+
35+
foreach ( $form['fields'] as $field ) {
36+
if ( $field['id'] != $field_id ) {
37+
continue;
38+
}
39+
40+
try {
41+
$api = new \GC_Notion\Notion_API_Client( $token );
42+
$response = $api->get_database( $database_id );
43+
44+
foreach ( $response['properties'] as $property ) {
45+
if ( rgar( $property, 'id' ) !== $property_id ) {
46+
continue;
47+
}
48+
49+
$type = rgar( $property, 'type' );
50+
$options = rgars( $property, $type . '/options' );
51+
$choices = array_map( function( $option ) {
52+
return array(
53+
'value' => $option['id'],
54+
'text' => $option['name'],
55+
);
56+
}, $options );
57+
58+
$field['choices'] = $choices;
59+
60+
break;
61+
}
62+
} catch ( \Exception $e ) {
63+
// noop
64+
}
65+
}
66+
67+
return $form;
68+
}, 10, 3);

0 commit comments

Comments
 (0)