0

This may be complicated to explain

I have a content type with field_1, field_2 etc

field_1 is a taxonomy reference

field_2 is a custom field with various sub-values

I have a custom formatter for field_2 which does all sorts of things to hang the sub-values into the desired output, however, I now have a condition for a certain value of field_1 which requires a different formatting to happen to field_2 that is not dependent on the field_2 values.

I need the formatter to handle this as the field will be required in various output scenarios (custom module, views, XML export) and I don't want to have to build multiple mechanisms for handling the data.

My question therefore is how I can grab field_1 from within the formatter of field_2 so that I can apply conditional format logic to it.

I could modify field_2 to contain a flag to control this formatting, however, there are > 20K records to add a value to whereas it's 1 additional field in a taxonomy record where there are less than 25 values, it would also allow an editor to set the formatting flag independently of the selected taxonomy and potentially an incorrectly displayed value. I can pass values to the formatter from custom module code, however, this needs to be applied when a "normal" user creates their own view or other brings back the field into a view or page.

Hope this makes sense

1 Answer 1

2

You can grab the host entity inside your field formatter with $items->getParent()->getEntity(), and then query all the other fields, e.g.:

class MyCustomFormatter extends FormatterBase {
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $parentEntity = $items->getParent()->getEntity();
    $otherFieldValue = $parentEntity->get('field_foo')->first()->getValue();
    foreach ($items as $delta => $item) {
      $elements[$delta] = your_custom_formatter_logic_here($otherFieldValue);
    }
    return $elements;
  }
}

If you are querying other entities in here, don't forget to merge those into $elements[$delta]['#cache']['tags']

1
  • Brilliant, that is really helpful and I guessed there had to be a very simple way. Commented Sep 6, 2021 at 14:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.