【问题标题】:Updating node fields on Drupal 8 programmatically以编程方式更新 Drupal 8 上的节点字段
【发布时间】:2021-10-05 05:23:42
【问题描述】:

我正在使用 Drupal 8 并尝试以编程方式更新以下节点的字段:

  • 已保存
  • 未发布

我希望能够同时发布多个节点,并让我的钩子运行,以编程方式将标准值添加到所有新发布的节点。

我在这里查看了解决方案: How to manipulate value before node is saved in Drupal 8? ...和这里: https://drupal.stackexchange.com/questions/304363/add-a-hero-image-and-text-when-a-node-goes-from-unpublished-to-published

...但是当我实施这些建议时(例如在我下面的代码中),我的内容节点上的字段没有被更新,它们保持为空。

如果您知道我如何更新此内容,请告知。谢谢。

模块结构:

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);
    }
  }
}

【问题讨论】:

  • 让我们添加一个日志或调试以确保您的钩子正在工作并且满足上述条件

标签: php drupal drupal-8


【解决方案1】:

您的代码的问题是,您试图将整个媒体实体设置为一个值 (target_id)。相反,您的字段“field_hero_image”可能是媒体引用字段,因此您只需要设置目标 ID。而且您已经知道目标 id (53),根本不需要加载媒体实体:

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

或者如果你想设置整个实体:

$entity->field_hero_image->entity = $media;

【讨论】:

  • 这解决了问题。谢谢@Paul
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 2017-09-28
  • 1970-01-01
相关资源
最近更新 更多