Search code examples
drupalnodeslimitdrupal-8user-accounts

Node limit per week for user group in Drupal 8


I have been trying to accomplish this:

Limit authenticated users (each one) to post only up to 3 articles per week. If they have already posted 3 articles this week, an error message will be shown and they will not be able to access the node/add/article page.

I tried to follow this (using Rules and Flag) but they do it per day using "Rules Once per Day" module witch is not available for D8.

I saw Node Limit module, but it crashes on my D8 after installation.

Any guidance and help on how to resolve this?

EDIT

You can find here (Github Link) the solution i made with the help from the selected answer.


Solution

  • I think the simple solution is to add a custom validation into the node form: when user tries to submit a new node (page, article ...), check if they posted up to 3 articles this week, if yes -> stop the form from submitting data, if no -> save new node.

    Here is my solution in code, which should be placed in your custom module:

    -- Implement hook_form_alter to add custom validation

    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';
      }
    }
    

    -- In custom validation function, check if current user posted up to 3 articles this week

    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)));
      }
    }
    

    Hope this help.