[Solved] Add a hero image and text when a node goes from unpublished to published

scaffolding Asks: Add a hero image and text when a node goes from unpublished to published
I’m trying to add a hero image and text when a node goes from unpublished to published. The things include:

  1. Add an image from my media library to a media field on the node
  2. Add a page title to the node, drawing upon a field already saved on the node

I’m attempting to build a hook on hook_node_update() but it’s not working. I’m not sure why.

The code I am using, part of the running_event_adding_header.module file, is the following.

Code:
namespace DrupalCoreFieldEntityReferenceFieldItemList;
namespace DrupalnodeEntity;


/**
 * Implements hook_node_update()
 */
 
function running_event_adding_header_node_update(DrupalCoreEntityEntityInterface $entity) {
  // End function if the entity is not an event
  if ($entity->bundle() !== 'event') {
    return;
  }
  
  // End function if the event is not a running type of event (running events are '30' in my system)
  if ($entity->bundle() === 'event' && $entity->get('field_event_type')->getString() != '30') {
      return;
  }

  // Check if the new state is "published" and the old state was something other than "published".

  if ($entity->get('moderation_state')->getString() === 'published') {

    /**
    * Add hero image and text to running event page, if not already present
    * The hero image field is 'field_hero_image'
    * The hero text field is 'field_tagline'
    */

    if ($entity->get('field_hero_image')->isEmpty()) {
      $media = Media::load(53); // 53 is the media ID for the image I'm wanting to load on all running pages: .../media/53/edit
      $entity->set('field_hero_image', $media);
    }

    //'field_tagline' is the hero title field
    if ($entity->get('field_tagline')->isEmpty()) {
      $entity->set('field_tagline', $entity->label());
    }
    $entity->save();  
  }
}//close function

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.