Hello!

We have some custom entities w/o bundles and we're using jsonapi to expose these to json api.

Now we'd like to add some dynamic data to json output without saving it to database. I'm having trouble figuring out how this module works on D8, since all docs seems to be for lesser versions.

I have the field set up like so:

    $fields['asiakas_nimi'] = BaseFieldDefinition::create('computed_string')
      ->setLabel(t('Asiakkaan nimi'))
      ->setDescription('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'asiakas_nimi_formatter',
        'weight' => 0,
      ]);

And custom formatter like so:

/**
 * Plugin implementation of the 'Example PHP' formatter for computed fields.
 *
 * @FieldFormatter(
 *   id = "asiakas_nimi_formatter",
 *   label = @Translation("Kaivaa asiakkaan nimen työmääräykselle"),
 *   field_types = {
 *     "computed_string",
 *   }
 * )
 */
class AsiakasNimiFormatter extends ComputedPhpFormatterBase {

  /**
   * Do something with the value before displaying it.
   *
   * @param mixed $value
   *   The (computed) value of the item.
   * @param \Drupal\Core\Field\FieldItemInterface $item
   *   The item to format for output
   * @param int $delta
   *   The delta value (index) of the item in case of multiple items
   * @param string $langcode
   *   The language code
   * @return mixed
   */
  public function formatItem($value, FieldItemInterface $item, $delta = 0, $langcode = NULL) {
    return 'ASIAKASNIMI' . $value;
  }
}

It seems that we have to save the entity before the field is present, this we can live with, but we're getting empty data in mentioned field no matter what we return in our formatter.

I'm pretty sure that we just do not know how to work with this module, so any help or documentation would be appreciated.

/ Janne

Comments

5to1 created an issue.