Score:0

How do I unset an entity reference using JSON:API?

cn flag

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?

Score:1
cn flag

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": {},
      }
    }
  }
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.