Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active March 30, 2022 18:48
Show Gist options
  • Save xnau/f3bce7c5bc7fdc3a85a2a15c8f736fe1 to your computer and use it in GitHub Desktop.
Save xnau/f3bce7c5bc7fdc3a85a2a15c8f736fe1 to your computer and use it in GitHub Desktop.
Demonstrates how to load a "Chosen" dropdown with options in Participants Database
<?php
/**
* Plugin Name: PDB Populate Chosen Dropdown
* Description: tests loading a chosen element with options
*
* sets our function to be called when the pdbcde-before_element_rendered action
* is triggered by the form just before the "Chosen Dropdown" is shown so we can
* change the list of options to show
*/
// attach our function to the pdbcde-before_element_rendered action
add_action( 'pdbcde-before_element_rendered', 'xnau_set_specialty_dropdown_options');
// this is needed when using a Chosen dropdown/other element
add_action( 'pdb-form_element_build_chosen-dropdown-other', 'xnau_set_specialty_dropdown_options');
/**
* sets the options for the "specialty" dropdown
*
* @global wpdb $wpdb
* @param PDb_FormElement object $field the current field
*/
function xnau_set_specialty_dropdown_options ( $field )
{
// this is the name of the field we want to add options to
$fieldname = 'specialty';
if ( $field->name === $fieldname ) : // check for our dropdown field
global $wpdb; // grab the db helper object
/*
* define the query for getting the list saved specialties
*
* note that the $wpdb->prefix method is used to get the table
* prefix; this is so it will work on all WP installs
*/
$query = '
SELECT DISTINCT `' . $fieldname . '`
FROM ' . $wpdb->prefix . 'participants_database
';
// now execute the query and get the results
$raw_names = $wpdb->get_results( $query );
/*
* now expand the result array into an array for the options
* property of the dropdown
*/
$options = $field->options;
foreach ( $raw_names as $record ) {
// this is the value we'll be considering
$new_value = $record->{$fieldname};
/*
* check the value against the defined options so we only
* add options that are not already in there
*/
if ( ! in_array( $new_value, $options ) ) {
// it's a new value, so add it to the dropdown options
$options[$new_value] = $new_value;
}
}
// now set the field object with the new options list
$field->options = $options;
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment