1
votes

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:

module_name
  module_name.info
  module_name.module

module_name.module:

<?php

namespace Drupal\Core\Field\EntityReferenceFieldItemList;
namespace Drupal\node\Entity;

//In the function below, I'm attempting to update
//'event' type nodes, specifically those with an event_type of '30'

//In those nodes, I'm attempting to use a Media library image 
//and use the page's title in the hero section


function module_name_node_presave(Drupal\node\NodeInterface $entity){
  if ($entity->bundle() === 'event' && $entity->get('field_event_type')->toString() === '30') {
    if ($entity->get('field_hero_tagline')->isEmpty()) {
      $entity->set('field_hero_tagline', $entity->label());
    }
    if ($entity->get('field_hero_image')->isEmpty()) {
      $media = Media::load(53); 
      $entity->set('field_hero_image', $media);
    }
  }
}

Let's add a log or debug to make sure that your hook is working and the above conditions are being satisfied - Kien Nguyen