Contentful logo

Contentful Community

How could I update empty fields in an existing content?

Hello,

I’ve been struggling for hours now, I hope someone could put me in the right direction.

I’m working on a project that retrieves some content from Contentful (I’m using the NPM contentful-management). I want to give the ability to some users to edit the content directly on a web page. Updating the content of an EXISTING populated field works perfectly:

    .then(entry => {
      entry.fields.title['en-US'] = 'Update entry title'
      // title has previously some content
      return entry.update()
    })

But my problem is when I want to update a field that exists in the content type but is EMPTY (with no content). As mentioned in the documentation:

Use this endpoint to fetch an entry with a specified ID. All empty entry fields are omitted from the response, that means if the field is empty it’s key is not going to be presented in the response. If the entry has no set fields the corresponding key is missing as well. In order to update the entry with empty fields all keys that need to be updated should be added to the entry object.

All empty entry fields are omitted from the response”, so when I do a .then(space => space.getEntry(entryId)), I only got the fields that are NOT empty so if I try to do:

    .then(entry => {
      entry.fields.description['en-US'] = 'New entry description'
      // description has NO previous content
      return entry.update()
    })

I obviously receive the following error: Cannot set property 'en-US' of undefined

What means In order to update the entry with empty fields all keys that need to be updated should be added to the entry object. from the documentation and how can I easily update empty fields?

Thank you!

Hi. You get an error because description is undefined so it cannot be indexed with [‘en-US’]. You just need to first create the key for the fields object, and you can at the same assign the value to it, like this:

entry.fields[‘description’] = {‘en-US’:‘New entry description’}

Hope this helps
Cristian

2 Likes

Hi @cristian.vidmar,

Thanks for your reply. Indeed it was a silly JavaScript mistake, I found the solution after I posted my question.

Thanks again!