drupaldrupal-permissionsdrupal-nodes

How to define custom access check function to see if a user may create a node in Drupal 7?


I have several things I want to check before a user may create a node. So, if the user visits node/add/proposal I want to check if he may do so, so I wrote a module:

function proposals_menu() {

    $items['node/add/proposal'] = array(
        'title' => t('Proposal'),
        'access callback' => 'proposals_access',
    );

    return $items;
}

function proposals_access() {
    $cond1;
    $cond2;
    ...

    return cond1 && cond2 && ....;
}

When I click on add content -> proposal I get a blank page. What am I missing?


Solution

  • To override existing menu items you need to use hook_menu_alter() instead of hook_menu(). e.g.

    function proposals_menu_alter(&$items) {
      $items['node/add/proposal']['access callback'] = 'some_function';
    }
    

    But there's also hook_node_access() which would be preferable to use for (as the name suggests) checking node access. e.g.

    function proposals_node_access($node, $op, $account) {
      $type = is_string($node) ? $node : $node->type;
    
      if ($type == 'proposal' && $op == 'create') {
        if ($allow_access) {
          return NODE_ACCESS_ALLOW;
        }
        else {
          return NODE_ACCESS_DENY;
        }
      }
      return NODE_ACCESS_IGNORE;
    }
    

    Assuming you populate $allow_access with your access check. Be sure to use the $account object that's passed to the hook to verify the operation against that user object. Don't depend on the currently logged in user, which will not always be the same.