0

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.)

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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