function hook_node_grants_alter

Same name in other branches
  1. 7.x modules/node/node.api.php \hook_node_grants_alter()
  2. 9 core/modules/node/node.api.php \hook_node_grants_alter()
  3. 8.9.x core/modules/node/node.api.php \hook_node_grants_alter()
  4. 11.x core/modules/node/node.api.php \hook_node_grants_alter()

Alter user access rules when trying to view, edit or delete a node.

Node access modules establish rules for user access to content. hook_node_grants() defines permissions for a user to view, edit or delete nodes by building a $grants array that indicates the permissions assigned to the user by each node access module. This hook is called to allow modules to modify the $grants array by reference, so the interaction of multiple node access modules can be altered or advanced business logic can be applied.

The resulting grants are then checked against the records stored in the {node_access} table to determine if the operation may be completed.

A module may deny all access to a user by setting $grants to an empty array.

Developers may use this hook to either add additional grants to a user or to remove existing grants. These rules are typically based on either the permissions assigned to a user role, or specific attributes of a user account.

Parameters

array $grants: The $grants array returned by hook_node_grants().

\Drupal\Core\Session\AccountInterface $account: The account requesting access to content.

string $operation: The operation being performed, 'view', 'update' or 'delete'.

See also

hook_node_grants()

hook_node_access_records()

hook_node_access_records_alter()

Related topics

1 function implements hook_node_grants_alter()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

node_test_node_grants_alter in core/modules/node/tests/modules/node_test/node_test.module
Implements hook_node_grants_alter().

File

core/modules/node/node.api.php, line 264

Code

function hook_node_grants_alter(&$grants, \Drupal\Core\Session\AccountInterface $account, $operation) {
    // Our sample module never allows certain roles to edit or delete
    // content. Since some other node access modules might allow this
    // permission, we expressly remove it by returning an empty $grants
    // array for roles specified in our variable setting.
    // Get our list of banned roles.
    $restricted = \Drupal::config('example.settings')->get('restricted_roles');
    if ($operation != 'view' && !empty($restricted)) {
        // Now check the roles for this account against the restrictions.
        foreach ($account->getRoles() as $rid) {
            if (in_array($rid, $restricted)) {
                $grants = [];
            }
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.