I'm trying to re-use the output from a heavily customized field formatter as <select><option>
text in a Webform. I managed to re-use field display, but it has the side-effect of switching the theme used for rendering.
Below is a simplified code, the lines $dateRenderArray = ...
and $dateHtml = ...
are original and cause the problem:
function mymodule_webform_options_alter(array &$options, array &$element, $options_id = NULL) {
foreach ($options as $value => $text) {
$entity = getEntityByOption($value);
//reuse custom field formatter output
$dateRenderArray = $entity->get('field_daterange')->view('teaser');
//the following line causes the theme change
$dateHtml = \Drupal::service('renderer')->renderPlain($dateRenderArray);
$datePlaintext = str_replace(["\n", " "], ["", " "], trim(strip_tags($dateHtml)));
$muchBetterOptionText = $someOtherPlaintextFromEntity . ' ' . $datePlaintext;
$options[$value] = $muchBetterOptionText;
}
}
This works excellent in the frontend form, for the submission emails and also in the admin webform submission list.
But in a single webform submission detail view, those lines cause an unwanted theme change from admin theme to frontend theme.
Question:
How can I prevent the theme change from renderPlain()
and keep the admin theme when viewing a single webform submission?
Optional bonus question:
Why does my hook work correctly in the webform submission list and not in webform submission detail view? The submission list uses exactly the same function, it renders the same processed option text in the corresponding column, but I do correctly stay inside the admin theme when viewing the list. But only in the detail view switches to the frontend theme.