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

281 views Asked by At

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?

2

There are 2 answers

0
Clive On BEST ANSWER

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.

0
lgomezma On

You get a blank page because you are not telling drupal how to render the path you are creating. For that you need to add a page callback to the item. As specified in the hook_menu documentation, this function will be called to display the page when the user visits the path.

 ...
$items['node/add/proposal'] = array(
        ...
        'page callback' => 'proposals_display_function'
    );
 ...