3

How can we restrict number of nodes allowed per content type. Let suppose if we allow 5 nodes then no one including the admin user can add the 6th node of that content type.

2

one possible solution to achieve the above is by checking the node count of that content type in hook_node_validate() as below:

/**
* Implements hook_node_validate().
*/
function MyModule_node_validate($node, $form, &$form_state) {
  // For now assign the static values to CONENT_TYPE and MAX_NODES
  // however you can make it dynamic, and get those values using variable_get().
  $content_type = 'CONTENT_TYPE';
  $max_nodes = 'MAX_NODES';
  $node_count = 0;

  // Create a check for the content type.
  if ((isset($node->type)) && ($node->type === $content_type)) {
    $query = new EntityFieldQuery;
    $node_count = $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', $content_type)
      // To get published nodes only, use: ->propertyCondition('status', 1)
      ->count()
      ->execute();

    // Check if the node count exceeds the max_node value.
    if ($node_count > $max_nodes) {
      form_set_error('FIELD_NAME', t('Reached the maximum limit of creation of nodes for this content type.'));
    }
  }
}

Similarly you can do with the Rules also, but the above method seems better to me.

  • Please make it a bit more easier for me to impliment, just let me know where to insert this code ? In template.php ?? – Fahad Oct 28 '13 at 18:05
  • @Fahad Insert the code in custom module file(.module), however don't forget to replace this values($content_type = 'CONTENT_TYPE'; $max_nodes = 'MAX_NODES';) with what you want. – Ankit Agrawal Oct 28 '13 at 18:09
  • I have created a module using your code changed the values of $content_type and $max_nodes turn on the module but its not working. I am still able to create new nodes of the content type which I want to restrict. – Fahad Oct 28 '13 at 18:50
  • I will accept it. Does this code restrict the user1 to create nodes ?? – Fahad Oct 28 '13 at 18:51
  • 1
    forget to change the function name MyModule. Works great now Thank you :) – Fahad Oct 28 '13 at 19:06
7

Have you tried the Node Limit module?

The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.

You could create a role just for node limit and assign ALL users (including the admin) to that role.

  • last time I saw that was not available for d7 still in alpha version, let me try it – Fahad Oct 18 '13 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.