This quick tutorial will let you limit the creation of a certain number of nodes for any user with a specific role. For every content type and/or role you want to limit, (Eg.: Contributors limited to 4 posts, Admins are limited to 10 posts), you will need to create a separate rule for each.
Assumptions:
- Are a familiar with Drupal 7.x and Rules 7.x
- You are familiar with PHP enough to read it.
Basics:
- A Content Type that you want to apply a limit to. Eg: "News Post"
- A Role that will be limited. Eg: "Contributor"
- A User with appropriate permissions to create "News Post", and has the role of "Contributor".
Modules:
- Rules (plus all dependancies)
- Rules Forms Support ( http://drupal.org/project/rules_forms)
Setup Rules Forms:
- Configure Rules Forms (Configuration -> Rules -> Form Events)
- Check ON:
- Enable event activation messages on forms
- Enable form element inspection tool
- Navigate to the node add form for your content type. Eg.: /node/add/news-post
- Click the link at the top of the form to enable the form events. Eg.: "Activate events for rules_forms_news_post"
- Refresh the node add page after it loads back
Create the Limiting Rule:
- Create a new Rule (Configuration -> Rules -> Add new rule)
- Name: "Contributor News Post Limit"
- React on event: "Rules Forms" -> "News Post node form is being built" -- where "News Post" is the name of the content type that you want limited, as mentioned in the above steps.
- Conditions:
- "User has role(s)"<- and add the role(s) that you want limited. Eg.: "Contributor"
- "Execute custom PHP code":
// Configure your settings: Node limit/quota & Content Type
$nodelimit = 10;
$content_type = 'news_post';
// Check it we are just editing an existing node, and quit if so
if(arg(0) == 'node'&& arg(2) == 'edit'){
return FALSE;
}
// Load the active user account
global $user;
// Drupal has a security feature called the Database Abstraction Layer.
// You have to build DB queries with variables that are defined in an array.
// Define the query string, where ":gdcuid" etc. are placeholders
$query = 'SELECT * FROM node WHERE uid=:gdcuid AND type=:gdctype';
// Define each placeholder
$variables = array(':gdcuid' => $user->uid, ':gdctype' => $content_type);
// Query the Drupal database
$result = db_query($query, $variables);
// Count the number of rows returned from the Drupal database
// From: http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7
$nodecount = $result->rowCount();
// Set the flag as to whether this Rule is effective or not
if ( $nodecount >= $nodelimit) {
return TRUE; // You will be over the accepted quota
} else {
return FALSE; // Still got room. Allow the new node.
}
- Actions:
- Show a message on the site: Warning: "You have reached your allotted limit of posts. Please delete old posts to make room, and try again".
- Page Redirect: ** Redirect to wherever you need, if you need **
Done. Feedback/improvements welcome!