Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shows how to find the optgroup of a field value in a Participants Database custom template.
<?php
$record = new PDb_Template( $this );
// name of the field you're interested in
$field = 'interests';
// get the array of defined options
$option_list = $record->get_field_prop( $field, 'options' );
// assume the title is blank at first
$optgroup_title = '';
$value_title = '';
// scan through the options, holding on to the last option title
foreach( $option_list as $title => $value ) {
if ( $value === 'optgroup' ) {
$optgroup_title = $title;
continue; // continue to the next option
}
// if the value matches, break and keep the last option title
if ( $value === $record->get_value( $field ) ) {
$value_title = $title;
break; // we found it, break out of the loop
}
}
// shows the result
echo $optgroup_title . ':' . $value_title;
@xnau

This comment has been minimized.

Copy link
Owner Author

@xnau xnau commented Sep 21, 2020

Note that this will not work as expected with multi-select type fields because the saved value is going to be an array.

If you want to do this with a multi-select, you can get the first value from the saved values with:

current( $record->get_value( $field ) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment