0

I'm trying to set the value of a taxonomy term entity reference field with a POST operation in JSON:API.

const data = {
  data: {
    type: 'node--page',
    attributes: {
      field_text: {
        value: `${values.textFieldValue}`,
        format: 'basic_html',
      },
      field_ref_term: {
        type: 'taxonomy-term--my-vocabulary',
        id: '9ca0cdc7-384c-4aa4-8ce9-d6c97fc2f44b',
      },
    },
  },
};

However, that gives me this error:

Unprocessable Entity: The following relationship fields were provided as attributes: [ field_ref_term ]

What am I supposed to do to fix this?

0

As the error indicates, the entity reference has to be set in relationships, not attributes.

The documentation gives this example:

{
  "data": {
    "type": "node--article",
    "attributes": {
      "title": "Article by admin",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    },
    "relationships": {
      "uid": {
        "data": {
          "type": "user--user",
          "id": "{{UUID of user 1}}"
        }
      }
    }
  }
}

In this example, the author of the node is set using the relationship of uid. However, it wasn't immediately clear to me how to set the entity reference field.

It turns out to be quite easy:

const data = {
  data: {
    type: 'node--page',
    attributes: {
      field_text: {
        value: `${values.textFieldValue}`,
        format: 'basic_html',
      },
    },
    relationships: {
      field_ref_term: {
        data: {
          type: 'taxonomy-term--my-vocabulary',
          id: '9fa0cdc7-384c-4aa4-8ce9-d6c97fc2f44b',
        },
      },
    },
  },
};

The key for the relationship is the machine name of the entity reference field.

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.