I've created Drupal 9 module with custom field formatter for many field types (string, entity_reference, image etc). I'm trying to implement twig editor in the formatter to control output. I need to have working {{ field_date_range }} {{ field_date_range.end_value }}
.
I tried to use $result = $field->view()
in viewElements()
for field, but when I add any custom variable to field before view it calls error (Element end_value isn't render array
). Also, when I did wrap of custom variable to #markup
it still visible when I haven't used it in twig.
The question is: Is it possible to implement? If it is, How?
To have better understanding what I'm talking about, I pinned screenshot.
Code:
class CustomTwigFormatter extends FormatterBase {
public static function defaultSettings() {
return [
'custom_markup' => '',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['custom_markup'] = [
'#type' => 'textarea',
'#title' => $this->t('HTML code'),
'#description' => $this->t('Twig and HTML tags allowed, e.g: @data', ['@data' => '<div>{{ field_name }}</div>']),
'#default_value' => $this->getSetting('custom_markup'),
];
return $form;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$field_groups = [];
foreach ($items as $item) {
$field_groups[$item->getFieldDefinition()->getName()][] = $item->view();
}
foreach ($field_groups as $field => $value) {
$elements[] = [
'#type' => 'inline_template',
'#template' => $this->getSetting('custom_markup'),
'#context' => [
$field => $value,
],
];
}
return $elements;
}
}