function field_formatter_filter_preprocess_field in Field Formatter Filter 8
Same name and namespace in other branches
- 7 field_formatter_filter.module \field_formatter_filter_preprocess_field()
- 2.0.x field_formatter_filter.module \field_formatter_filter_preprocess_field()
Applies an additional filter on the text field being rendered.
Implements hook_preprocess_HOOK().
Parameters
array $variables: Theme variables.
File
- ./
field_formatter_filter.module, line 86 - Allows different text format filters to be applied to text fields.
Code
function field_formatter_filter_preprocess_field(array &$variables) {
// This runs on all fields all the time - surely that's overkill?
// Can I inject instructions further upstream?
// It feels this hook is a bit late.
// Also, it's a hook. Whither plugins?
$element = $variables['element'];
// Only process recognised text formatters.
if (!_field_formatter_filter_target_field_type($element['#field_type'])) {
return;
}
// Get a few convenient handles.
/* @var $entity \Drupal\Core\Entity\FieldableEntityInterface */
$entity = $variables['element']['#object'];
$field_name = $variables['element']['#field_name'];
$view_mode = $variables['element']['#view_mode'];
// Drill down to field formatter settings.
$render_display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
$field_display = $render_display
->getComponent($field_name);
if (empty($field_display['third_party_settings']['field_formatter_filter']['format'])) {
return;
}
$format_id = $field_display['third_party_settings']['field_formatter_filter']['format'];
// Avoid problems if the named format was invalid, such being deleted.
if (!FilterFormat::load($format_id)) {
// This is rare and wrong enough to warn loudly about.
// Be as informative as we can.
$message = "The %field_name field displayed on the %view_mode view of %bundle %entity_type was set to use text format '%format_id' - which is invalid or unavailable. Default rendering will be used until this is fixed.";
$strings = [
'%field_name' => $field_name,
'%view_mode' => $view_mode,
'%bundle' => $entity
->bundle(),
'%entity_type' => $entity
->getEntityTypeId(),
'%format_id' => $format_id,
];
\Drupal::logger('field_formatter_filter')
->warning($message, $strings);
return;
}
$children_keys = Element::children($element);
foreach ($children_keys as $key) {
/*
* REPLACE the expected format rule.
* When the render process eventually hits
* @see Drupal\filter\Element\ProcessedText::preRenderText
* It will use my given format.
*/
$variables['items'][$key]['content']['#format'] = $format_id;
/*
* Or,
* ADD my process to the $variables['items']['content'][#pre_render']
* array.
* $variables[$key]['#pre_render'][] = [];
*/
}
}