You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal 8技术问询:如何按特定时段调度或隐藏内容类型节点字段

如何在Drupal 8中针对特定内容类型的节点字段按指定时间段调度配置?

嘿,我来帮你搞定这个Drupal 8的字段调度需求!针对你提到的「认证用户在特定日期后才能看到文章(article)类型的正文(body)字段」场景,我整理了两种实用方案,你可以根据自己的技术能力选择:


方案一:使用Scheduled Fields模块(非代码方式)

这是最省心的方法,不需要写代码,适合大部分管理员:

  • 安装模块:在Drupal后台的「扩展」页面搜索并安装Scheduled Fields模块(注意选择适配Drupal 8的版本,确认模块维护状态)。
  • 配置字段调度规则:
    1. 进入「结构」→「内容类型」→「文章」→「管理字段」,找到「正文(body)」字段,点击「编辑」。
    2. 滚动到页面底部的「Scheduled Fields」配置区域,点击「添加规则」。
    3. 规则类型选择「可见性」,用户角色勾选「认证用户」,时间条件设置为「在[你指定的日期时间]之后」。
    4. 保存字段配置。
  • 测试效果:用认证用户账号登录,在指定日期前查看文章,body字段会被隐藏;日期到达后,字段自动对认证用户可见。

方案二:自定义代码实现(无需额外模块)

如果你不想依赖第三方模块,或者需要更灵活的逻辑,可以用自定义代码实现:

  • 创建自定义模块:
    1. 在modules/custom目录下新建一个名为custom_field_schedule的文件夹。
    2. 创建custom_field_schedule.info.yml文件,内容如下:
      name: 'Custom Field Schedule'
      type: module
      description: 'Schedule field visibility for authenticated users.'
      core: 8.x
      package: Custom
      
  • 编写钩子代码:
    在模块文件夹下创建custom_field_schedule.module文件,添加以下代码:
    <?php
    
    /**
     * Implements hook_preprocess_field().
     */
    function custom_field_schedule_preprocess_field(&$variables) {
      // 仅针对文章类型的body字段
      if ($variables['field_name'] !== 'body' || $variables['element']['#bundle'] !== 'article') {
        return;
      }
    
      // 检查当前用户是否为认证用户
      $current_user = \Drupal::currentUser();
      if (!$current_user->isAuthenticated()) {
        return;
      }
    
      // 设置目标日期时间(这里改成你需要的日期,格式:Y-m-d H:i:s)
      $target_datetime = '2024-10-01 00:00:00';
      $target_timestamp = strtotime($target_datetime);
      $current_timestamp = \Drupal::time()->getCurrentTime();
    
      // 如果当前时间早于目标日期,隐藏字段
      if ($current_timestamp < $target_timestamp) {
        // 清空字段内容
        $variables['items'] = [];
        // 或者添加隐藏属性
        $variables['attributes']['hidden'] = TRUE;
      }
    
      // 添加缓存上下文,避免缓存导致的显示异常
      $variables['#cache']['contexts'][] = 'user.roles:authenticated';
      $variables['#cache']['contexts'][] = 'time';
    }
    
  • 启用模块并测试:在后台扩展页面启用「Custom Field Schedule」模块,清一下Drupal缓存,然后按需求测试即可。

额外注意事项

  • 模块方案要确保Scheduled Fields模块与你的Drupal 8版本兼容,避免出现兼容性问题;
  • 自定义代码中的目标日期可以改成可配置项(比如新增一个配置表单),这样不需要修改代码就能调整时间;
  • 测试时如果遇到缓存问题,记得清空Drupal的页面缓存和动态缓存,确保规则生效。

内容的提问来源于stack exchange,提问作者Gagan Shukla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:19:53