2

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.field formatter settings

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;
  }
}
2
  • $item->view() looks like a recursive call to the same field formatter (if this field formatter is configured as default). If you want to reuse core field formatting then extend the core class and call the parent method.
    – 4uk4
    Sep 26, 2022 at 12:45
  • Wrong comment, $item->view('default') will do recursive call, because view mode. Sep 29, 2022 at 8:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.