drupal - Drupal 8 中用户组每周的节点限制
问题描述
我一直在努力做到这一点:
将经过身份验证的用户(每人)限制为每周最多发布 3 篇文章。如果他们本周已经发布了 3 篇文章,则会显示一条错误消息,并且他们将无法访问节点/添加/文章页面。
我试图遵循这一点(使用Rules和Flag),但他们每天都使用“每天一次的规则”模块来做这件事,这对 D8 不可用。
我看到了Node Limit模块,但安装后它在我的 D8 上崩溃了。
有关如何解决此问题的任何指导和帮助?
编辑
您可以在此处(Github 链接)找到我在所选答案的帮助下做出的解决方案。
解决方案
我认为简单的解决方案是在节点表单中添加自定义验证:当用户尝试提交新节点(页面、文章...)时,检查他们本周是否发布了 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)));
}
}
希望这有帮助。
推荐阅读
- extjs - 列标题中有省略号时的 ExtJS 工具提示
- function - Google 表格 SKU 自动数据
- laravel - Laravel 如何轻松过滤 Eloquent 的所有内容?
- sql - tsql - 员工的枢轴总和
- python - 如何仅将引导样式应用于 django-crispy-forms 而不是 html 模板中的其他标签
- javascript - 如何获取html画布标签的坐标
- excel - VBA - 试图获取函数的根
- c# - 我试图在字符串和重复指令的帮助下解决的问题,但在控制台上结果不是我所期望的
- laravel - laravel,使用foreach按id获取数据
- flutter - Flutter 中的 Inflating StatefullWidget 是什么意思?