For a headless Drupal backend, that is used mainly as a jsonApi endpoint, I added to nodes in general a field, that contains node translation paths (if created).

With that I am able to show a menu switcher in the frontend without the need to create another request.

I created a field, that is just a computed output by creating a FileItemList object. This also works - but I have two issues.


namespace Drupal\test_json_logic\Plugin\Field;

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

class TranslatedPaths extends FieldItemList {

  use ComputedItemListTrait;

   * Computes the field value.
  protected function computeValue() {
    $node = $this->getEntity();

    // Get all activated languages.
    $languages = \Drupal::languageManager()->getLanguages();
    $return = [];
    if ($node->id()) {
      foreach ($languages as $language) {

        // Get the current URL in each language.
        $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $node->id()])
          ->setOption('language', $language)->toString();
        if (!str_contains($url, '/node/')) {
          $return[$language->getId()] = $url;
        else {
          $return[$language->getId()] = '';
      $this->list[0] = $this->createItem(0, json_encode($return));

1st issue: I cannot save the translation setting page (/admin/config/regional/content-language). I receive the following error now:

Drupal\Core\Field\FieldException: Attempt to create a base field bundle override of field Translated Paths without an entity_type in Drupal\Core\Field\Entity\BaseFieldOverride->__construct() (line 99 of core/lib/Drupal/Core/Field/Entity/BaseFieldOverride.php).

2nd issue: What I really want to output is an array - (in the jsonApi export). This was not possible - so before I had to turn the data into an jsonString which is kind of double work as Drupal does it automatically for every jsonApi output. I really don't know which should be the correct way. I understand, that in theory the field is not just used in the jsonApi but I don't need specific form widgets - just a clean array with just the values I need.


Your Answer

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

Browse other questions tagged or ask your own question.