Score:0

How to assign a paragraph to a node correctly?

tf flag

I'm currently facing an issue while trying to link paragraphs to a content type in a newer version of Drupal. I have data from an older Drupal website that I need to migrate to a more updated Drupal version. I'm using the JSON:API to achieve this, but I'm encountering problems in associating paragraphs with a specific field in the content type.

Here's an overview of the process and the code involved:

  1. I retrieve data from an older website's endpoint using JSON:API. The fetched data is stored in the currentData object, which contains both data and included arrays.
  2. For each medical profile data fetched from the older site, I create a new node of the content type medical_profile in the newer site using the JSON:API.
  3. Paragraphs are created and stored in an array called paragraphs. Each item in this array has the type and id of the paragraph.
  4. Finally, I use the axios.patch method to update the node of the medical_profile content type and associate the created paragraphs with the field_conteudo field using the paragraphs array.
const createParagraphContent = async (id, medicalNid) => {
  const paragraphContent = currentData.included.find(element => element.id === id);

  const newParagraph = {
    type: 'paragraph--descricao_profissional',
    attributes: {
      field_label: paragraphContent.attributes['field_text_120'],
      field_texto: {
        value: paragraphContent.attributes['field_richtext']['value'],
        format: 'cohesion',
      },
      parent_id: medicalNid,
      parent_type: "node",
      parent_field_name: "field_conteudo",
    },
  };

  const axiosConfig = {
    headers: {
      'Content-Type': 'application/vnd.api+json',
      Authorization: authHeader,
    },
  };

  try {
    const response = await axios.post(`${process.env.EQUALIZACAO_SITE_URL}/jsonapi/paragraph/descricao_profissional`, { data: newParagraph }, axiosConfig);
    return response.data.data.id
  } catch (error) {
    console.error('Erro ao criar novo paragraph:', error);
    return error;
  }
}

The block bellow is the usage of this function

const response = await axios.post(`${process.env.EQUALIZACAO_SITE_URL}/jsonapi/node/medical_profile`, { data: newMedicalProfile }, axiosConfig);

      const paragraphs = [];
      for (let idx = 0; idx < element.relationships.field_label_input.data.length; idx++) {
        const elementTwo = element.relationships.field_label_input.data[idx];        
        paragraphs.push({
          type: 'paragraph--descricao_profissional',
          id: await createParagraphContent(elementTwo.id, response.data.data.attributes.drupal_internal__nid)
        })
      }

      const responseParagraphs = await axios.patch(`${process.env.EQUALIZACAO_SITE_URL}/jsonapi/node/medical_profile/${response.data.data.id}`, { data: {
        type: "node--medical_profile",
        id: response.data.data.id,
        relationships: {
          field_conteudo: {
            data: paragraphs
          }
        }
      } }, axiosConfig);

paragraphs array looks like this:

[
  {
    type: 'paragraph--descricao_profissional',
    id: 'fb01c352-2f1f-4a3f-b730-d8e298a2b271'
  }
]

Thank you for your time and assistance!

@edit: After receiving assistance from Giuseppe, I've made a few changes to my approach.

I've updated the createParagraphContent function to return the complete entity object instead of just the ID:

 try {
    const response = await axios.post(`${process.env.EQUALIZACAO_SITE_URL}/jsonapi/paragraph/descricao_profissional`, { data: newParagraph }, axiosConfig);
    return response.data.data
  } catch (error) {
    console.error('Erro ao criar novo paragraph:', error);
    return error;
  }

And some changes at paragraphs loop:


      const paragraphs = [];
      for (let idx = 0; idx < element.relationships.field_label_input.data.length; idx++) {
        const elementTwo = element.relationships.field_label_input.data[idx];
        const newParagraph = await createParagraphContent(elementTwo.id, response.data.data.attributes.drupal_internal__nid)
        paragraphs.push({
          type: 'paragraph--descricao_profissional',
          id: newParagraph.id,
          meta: {
            target_revision_id: newParagraph.attributes.drupal_internal__revision_id
          }
        })
      }

Score:0
br flag

For entity reference revisions it's necessary to specify also the target_revision_id

So, your paragraphs' array should be something like:

[
  {
    type: 'paragraph--descricao_profissional',
    id: 'fb01c352-2f1f-4a3f-b730-d8e298a2b271'
            "meta": {
              "target_revision_id": 120
            }
  }
]

By the way, be careful in case you PATCH paragraphs via JSON:API because the same applies, so you need to update the target_revision_id on the node, otherwise it will referer the "old" paragraph.

Tercio Lacerda avatar
tf flag
Works perfectly, thank for the help Giuseppe!
I sit in a Tesla and translated this thread with Ai:

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.