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.
validate
method and then usehook_entity_bundle_field_info_alter
to add constraint.