0

I can't figure out how to unset an entity reference (remove a reference to a term from a node) when editing content via JSON:API.

JSON to create a new node:

  const myNodeToPost = {
    data: {
      type: 'my_node_type',
      attributes: {
        body: {
          value: `${bodyText}`,
          format: 'basic_html',
        },
      },
      relationships: {
        refTerm: {
          data: {
            type: 'taxonomyType',
            id: `${taxonomyTermUuid}`,
          },
        },
      },
    },

The node is posted, and the taxonomy term is referenced correctly.

The entity reference to the taxonomy term is not required. So, users can remove the term reference when editing the node.

When editing a node, if I PATCH to JSON:API without referring to the entity reference, the node is updated, but the entity reference remains in place.

  const myEditedNode = {
    data: {
      type: 'my_node_type',
      attributes: {
        body: {
          value: `${bodyText}`,
          format: 'basic_html',
        },
      },
    },

So, I tried setting the ID to null:

  const myEditedNode = {
    data: {
      type: 'my_node_type',
      attributes: {
        body: {
          value: `${bodyText}`,
          format: 'basic_html',
        },
      },
      relationships: {
        refTerm: {
          data: {
            type: 'taxonomyType',
            id: null,
          },
        },
      },
    },

However, this gives a 400 Bad Request: No ID specified for related resource.

How can I remove an entity reference with JSON:API?

1 Answer 1

1

Thanks to franck_lorancy on drupal.org, I managed to fix this and it is now part of the documentation for PATCH:

{
  "data": {
    "type": "node--article",
    "id": "{{article_uuid}}",
    "attributes": {
      "title": "My updated title",
      "body": {
        "value": "Updated body text",
        "format": "plain_text",
        "summary": "Updated summary"
      }
    },
    "relationships": {
      "my_entity_reference_field": {
        "data": {},
      }
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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