Drupal 8 中用户组的每周节点限制

Node limit per week for user group in Drupal 8

我一直在努力做到这一点:

限制经过身份验证的用户(每个)post 每周最多只能阅读 3 篇文章。如果他们本周已经 post 发表了 3 篇文章,将显示一条错误消息,他们将无法访问 node/add/article 页面。

我尝试遵循 this(使用 规则Flag)但他们每天都使用 "Rules Once per Day" 模块 不适用于 D8。

我看到了 Node Limit 模块,但安装后它在我的 D8 上崩溃了。

任何有关如何解决此问题的指导和帮助?

编辑

您可以在这里(Github Link)找到我在所选答案的帮助下做出的解决方案。

我认为简单的解决方案是在节点表单中添加自定义验证:当用户尝试提交新节点(页面、文章...)时,检查他们本周是否最多发布了 3 篇文章,如果是 -> 停止表单提交数据,如果否 -> 保存新节点。

这是我的代码解决方案,应该放在您的自定义模块中:

-- 实现hook_form_alter 添加自定义验证

function MY_MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // check if user is about to create new node of type page
  // This custom validation won't be called on EDIT form (edit form_id is node_page_edit_form)
  if($form_id == 'node_page_form') {
    $form['#validate'][] = '_node_page_form_custom_validate';
  }
}

-- 在自定义验证函数中,检查当前用户本周是否发布了最多 3 篇文章

function _node_page_form_custom_validate(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // 1. get current user id
  $user_uid = \Drupal::currentUser()->id();

  // 2. count number of nodes created by current user in last week
  $query = \Drupal::entityQuery('node');
  $query->condition('type', array('page', 'article'), 'IN'); // Limit the type of node to check
  $query->condition('uid', $user_uid);

  $first_day_of_week = strtotime('Last Monday'); // choose the day you define as First day of week
  $last_day_of_week = strtotime('Next Monday');
  $query->condition('created', array($first_day_of_week, $last_day_of_week), 'BETWEEN');

  $count = $query->count()->execute();

  // 3. if number of posts reachs limit, stop the form from saving data
  if($count >= 3) {
    $form_state->setErrorByName('', t('You reached the limit of @count pages/articles this week', array('@count' => $count)));
  }
}

希望对您有所帮助。