php - 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 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);
}
}
}
Answer
Solution:
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;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: ftp_put(): can't open that file: no such file or directory
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.