Skip to content
Advertisement

Updating node fields on Drupal 8 programmatically

I’m using Drupal 8 and trying to programmatically update fields of nodes that are:

  • already saved
  • unpublished

I’d like to be able to publish multiple nodes at the same time, and have my hook run, programmatically adding standard values to all newly-published nodes.

I’ve looked at the solutions here: How to manipulate value before node is saved in Drupal 8? …and here: https://drupal.stackexchange.com/questions/304363/add-a-hero-image-and-text-when-a-node-goes-from-unpublished-to-published

…but when I implement these recommendations (e.g. in my code below), the fields on my content nodes are not being updated, they remain empty.

If you know how I can update this, please advise. Thank you.

Module structure:

JavaScript

module_name.module:

JavaScript

Advertisement

Answer

The problem with your code is, that you are trying to set the whole media entity as a value (target_id). Instead, your field “field_hero_image” is probably a media reference field and thus you only need to set the target id. And as you already know the target id (53), there is no need to load the media entity at all:

JavaScript

or if you want to set the whole entity:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement