Score:0

Find value of another field in a fieldformatter

in flag

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

Score:0
ru flag

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']

Alex Monaghan avatar
in flag
Brilliant, that is really helpful and I guessed there had to be a very simple way.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.