Score:0

Access FieldItem object from Widget

in flag

I have a custom FieldItem with a method doing a calculation on the field's values:

class MyFieldItem extends FieldItemBase {
  ...
  public function getAmountInEuros() {
    $amount = $this->get('amount')->getValue();
    $currency = $this->get('currency')->getValue();
    $exchange_rate = $this->getExchangeRate($currency);
    return $exchange_rate * $amount;
  }
  ...

I have a custom widget for that FieldItem where I need to do exactly the same calculation.

class MyWidget extends WidgetBase {
  ...
  public function getAmountInEuros() {
    ...
  }
  ...
}

Of course, I would prefer to write down this logic only in one place, preferably in the FieldItem definition.

How can I access the corresponding FieldItem from within the widget?

(The code is just a minimal example that should show the principal problem with a complex field and widget that work otherwise.)

Score:1
cn flag

If you are building a single form element you have $delta to get the field item.

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

  $euros = $items[$delta]->getAmountInEuros();

In other widget methods you can loop over $items.

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.