Drupal 8:特定内容类型Node创建/更新时更新用户的方案
解决Drupal 8中特定内容类型Node创建/更新时触发用户操作的问题
嘿,刚接触Drupal 8能找到hook_entity_create已经很不错啦!不过它确实只负责实体创建的场景,要同时覆盖创建和更新两种情况,这里有两个实用的方案,你可以根据自己的需求选:
方案一:用hook_entity_presave(推荐)
这个钩子是个「全能选手」——不管是新建Node准备保存,还是编辑现有Node后保存,它都会触发,完美匹配你的需求。代码示例如下:
/** * Implements hook_entity_presave(). */ function your_custom_module_entity_presave(Drupal\Core\Entity\EntityInterface $entity) { // 先判断是不是Node类型的实体 if ($entity->getEntityTypeId() !== 'node') { return; } // 指定你要监听的内容类型,比如换成你自己的'news'或者'product' $target_content_type = 'article'; if ($entity->bundle() !== $target_content_type) { return; } // 到这里就可以写你的用户更新操作逻辑了 // 举个例子:获取节点的作者并更新其字段 $user = $entity->getOwner(); if ($user) { // 比如给用户添加一个自定义字段值,或者修改角色 // $user->set('field_custom', 'updated_value'); // $user->save(); } }
为什么推荐这个?
- 只需要写一次逻辑,就能覆盖创建和更新两种场景
- 不仅适用于Node,其他实体类型也能复用这个钩子(如果以后有需求的话)
方案二:分开用hook_node_insert和hook_node_update
如果你觉得分开处理创建和更新的逻辑更清晰,或者以后需要给两种场景加不同的操作,可以用Node专属的这两个钩子,然后把公共逻辑封装起来避免重复代码:
/** * Implements hook_node_insert(). * Node创建时触发 */ function your_custom_module_node_insert(Drupal\node\NodeInterface $node) { _your_custom_module_update_user($node); } /** * Implements hook_node_update(). * Node更新时触发 */ function your_custom_module_node_update(Drupal\node\NodeInterface $node) { _your_custom_module_update_user($node); } /** * 封装公共的用户更新逻辑 */ function _your_custom_module_update_user(Drupal\node\NodeInterface $node) { // 同样先判断目标内容类型 if ($node->bundle() !== 'article') { return; } // 这里写你的用户更新操作 }
小提醒
- 记得把代码里的
your_custom_module换成你自己的模块名称 - 执行用户更新操作时,要确保你的模块有对应的权限(比如编辑用户的权限)
- 调试的时候可以加日志确认钩子是否触发:
然后去报告 > 最近的日志消息里查看\Drupal::logger('your_custom_module')->notice('Node @type 已触发用户更新操作', ['@type' => $node->bundle()]);
内容的提问来源于stack exchange,提问作者user9152788




