【发布时间】: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);
}
}
}
【问题讨论】:
-
让我们添加一个日志或调试以确保您的钩子正在工作并且满足上述条件