0

I am recreating my website from Drupal 7 to Drupal 9, and I am struggling with getting a rule that I had setup in D7 working on D9. Rules is still in Alpha, and the Rules Form module is non-existent for D8/D9 so I do not want to attempt to use Rules for this.

I want to limit the number of nodes a user can create by node type and role. Currently the code I have in D7 Rules is:

// Configure your settings: Node limit/quota & Content Type
$nodelimit = 3;
$content_type = 'car';

// 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 ":drupaluid" etc. are arbitrary placeholders
$query = 'SELECT * FROM {node} WHERE uid=:drupaluid AND type=:drupaltype';

// Define each placeholder
$variables = array(':drupaluid' => $user->uid, ':drupaltype' => $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.
} 

If this returns true, I then have a Rules action that forwards the user to a specific page instead of the node create form.

However I am not a programmer, and I am struggling to figure out how to do this in D9 without rules. It looks like maybe I could create a small module and use "function hook_node_access"? I'm also not sure if the API's that are called in the code above for D7 will work in D9? The code above also does not "forward" to another page if true, as I was using Rules to do that.

3
  • You can do that by creating a custom constraint . Refer drupal.stackexchange.com/questions/294733/… and drupal.stackexchange.com/a/300294 for reference. Add all your logic in validate method and then use hook_entity_bundle_field_info_alter to add constraint. Commented Apr 6, 2021 at 10:56
  • I guess I'm not following. I read through those pages, and also your comment all are validating a field. What field would this be? I'm picturing this firing from the form creation, before any fields would by queried. Commented Apr 6, 2021 at 18:09
  • You can validate title as it will be present in all node bundles. If criteria is met it will fire the message. Commented Apr 6, 2021 at 22:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.