hook_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account)
Controls access to a node.
Modules may implement this hook if they want to have a say in whether or not a given user has access to perform a given operation on a node.
The administrative account (user ID #1) always passes any access check, so this hook is not called in that case. Users with the "bypass node access" permission may always view and edit content through the administrative interface.
Note that not all modules will want to influence access on all node types. If your module does not want to explicitly allow or forbid access, return an AccessResultInterface object with neither isAllowed() nor isForbidden() equaling TRUE. Blindly returning an object with isForbidden() equaling TRUE will break other node access modules.
Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.) See Node access rights for a full explanation.
Parameters
\Drupal\node\NodeInterface|string $node: Either a node entity or the machine name of the content type on which to perform the access check.
string $op: The operation to be performed. Possible values:
- "create"
- "delete"
- "update"
- "view"
\Drupal\Core\Session\AccountInterface $account: The user object to perform the access check operation on.
Return value
\Drupal\Core\Access\AccessResultInterface The access result.
Related topics
- Hooks
- Define functions that alter the behavior of Drupal core.
- Node access rights
- The node access system determines who can do what to which nodes.
File
- core/modules/node/node.api.php, line 327
- Hooks specific to the Node module.
Code
function hook_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) { $type = $node->bundle(); switch ($op) { case 'create': return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content'); case 'update': if ($account->hasPermission('edit any ' . $type . ' content', $account)) { return AccessResult::allowed()->cachePerPermissions(); } else { return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node); } case 'delete': if ($account->hasPermission('delete any ' . $type . ' content', $account)) { return AccessResult::allowed()->cachePerPermissions(); } else { return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node); } default: // No opinion. return AccessResult::neutral(); } }
Please login to continue.