From bf54ae84891f4dfb6fb8ec45ad9db47c40ba66c1 Mon Sep 17 00:00:00 2001 From: Peter Oslington Date: Mon, 4 Jul 2022 15:35:43 +1000 Subject: [PATCH] Implemented trying several fields in api shortcode --- USAGE.md | 1 + shortcodes/civicrm/api4-get.php | 24 ++++++++++++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/USAGE.md b/USAGE.md index 8aa70e6..9a6a5c3 100644 --- a/USAGE.md +++ b/USAGE.md @@ -189,6 +189,7 @@ Limited format support is available: * Date fields can have their format specified with the same format as [CiviCRM's date display](https://docs.civicrm.org/user/en/latest/initial-set-up/dates/), e.g. `[api4:start_date:%B %E, %Y]` * File upload fields can be output as images with width, height, and alt text specified, e.g. `[api4:My_Custom_Field_Group.Image_Upload:img:800x300:alt=A picture]` * A line break tag can be output with fields only when they contain data with `:br`, e.g. `[api4:My_Custom_Field_Group.Optional_Field:br]` +* Conditional display of fields has some support, using `[api4:display_name|sort_name]` syntax, which will return the `display_name` if defined, then the `sort_name` if defined. Formatting options cannot be applied conditionally, so this should only be used for the same content type (i.e. don't mix text/images in results, as this may apply invalid formatting options). ### CiviCRM API trouble-shooting diff --git a/shortcodes/civicrm/api4-get.php b/shortcodes/civicrm/api4-get.php index 34db913..cdedff0 100644 --- a/shortcodes/civicrm/api4-get.php +++ b/shortcodes/civicrm/api4-get.php @@ -103,7 +103,10 @@ public function shortcode_callback( $atts = [], $content = NULL, $tag = '' ) { $output_regex = '/ (?: ( \[ ) | ( {{ ) ) api4: (? [^][[:space:]:{}]+ (?::(?:label|value|name|id))?) (?: : (? [^][{}]+ ) )? (?(1) \] | }} ) /sx'; if ( preg_match_all( $output_regex, $content, $match ) ) { - $params['select'] = array_values( $match['field'] ); + $params['select'] = array(); + foreach ( $match['field'] as $field ) { + $params['select'] = array_merge($params['select'], explode( '|', $field)); + } } $params = apply_filters( $this->get_shortcode_name() . '/params', $params, $atts ); @@ -136,11 +139,20 @@ public function shortcode_callback( $atts = [], $content = NULL, $tag = '' ) { foreach ( $results as $result ) { $output = preg_replace_callback( $output_regex, function ( $match ) use ( $result, $fields ) { - $output = $result[ $match['field'] ] ?? ''; - - if ( ! $output ) { - return ''; - } + + $field_array = explode( '|', $match['field']); + + while ( ! $output ) { + if ( 1 > count( $field_array ) ) { + return ''; + } + $current = array_shift( $field_array ); + if ( $result[$current] ) { + $output = $result[$current]; + } + } + + $match['field'] = $current; $field = $fields[ $match['field'] ] ?? [];