2

I'm working on a custom node access module. For this I'm working with hook_node_access hook (for the first time).

I want visitors to be able to view a node only when they are looking at them from the right domain. For this I have a content type page, in this content type I created a field field_domain.

Now I create a two nodes, Node A with field_domain value d9-a.lcl and Node B with field_domain value d9-b.lcl.

Now I wanted to create the module based on the this tutorial. But before this I created a simple check to see if I can get the value from the field and current domain. So I wrote this:

function hook_access_node_access(NodeInterface $node, $op, $account)
{
    $type = $node->bundle();
    if ($type == 'page') {
        $currentDomain = $_SERVER['SERVER_NAME'];
        $readerDomain = $node->field_domain->value;
        dpm($node->id());
        dpm('Current domain: ' . $currentDomain);
        dpm('Pages domain: ' . $readerDomain);
    }
}

Now going to Node B from domain d9-b.lcl made me expect to see three values. And the values I wanted to see are there but they get returned three times.

enter image description here

So for some reason the hook is called three times and I can't figure out why. Is it normal that this hook is called three times? And if it is is there a better way to do what I want?

7
  • 6
    Yes it’s perfectly usual for a node access hook to be hit multiple times in one request, check the $op parameter to see what you’re dealing with each time
    – Clive
    Nov 4, 2020 at 15:03
  • If you want more details you can use debug_backtrace function and print the result (or use a debugger).
    – sanzante
    Nov 4, 2020 at 15:06
  • 4
    Thanks @Clive it was indeed running three times because of the three access levels view,update and delete foud in $op.
    – Joost
    Nov 4, 2020 at 15:15
  • Those three access check manage the tabs you can see or not on your content (view / edit / delete tabs)
    – MacSim
    Nov 4, 2020 at 16:20
  • @Clive why do you answer in a comment? Please give the answer in the proper place so that can be accepted and this question marked as answered. Thanks
    – dxvargas
    Nov 4, 2020 at 17:52

1 Answer 1

2

Yes it’s perfectly usual for a node access hook to be hit multiple times in one request, check the $op parameter to see what you’re dealing with each time.

Checks may be done for different $op values like view,update and delete.

(Answer from @Clive in comments, posted here as answer after his advice. Please see question's comments.)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.