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:

module_name
  module_name.info
  module_name.module

module_name.module:

<?php

namespace DrupalCoreFieldEntityReferenceFieldItemList;
namespace DrupalnodeEntity;

//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(DrupalnodeNodeInterface $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);
    }
  }
}

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:

$entity->set('field_hero_image', 53);

or if you want to set the whole entity:

$entity->field_hero_image->entity = $media;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement