简体   繁体   中英

Drupal - Node-form objects visibility by role

I'm in the process of theming a node form. I want authenticated users to have as few fields as possible, while I as an administrator want to see all fields. How do I write a php if statement that checks if the current logged in user is an administrator?

global $user;

// Check to see if $user has the administrator role.
if (in_array('administrator', array_values($user->roles))) {
// Do something.
}

When on nodes, there is also a $is_admin variable available (not sure if it's in always the case). For more infos on the user, the $user array will hold all needed infos

There seems to be some ambiguity here. You can control the display of fields to end users using the above code in a theme template. It will not affect the display of fields in the content edit or create forms. To do that, you'll likely want to use field_permissions (part of cck) which limits access to fields based on role.

CCK内容权限。

It is non-standard practice to control which fields a user sees via the theming layer. It's better to use the access control system properly, that way other developers will know how to tweak things back again for their own changes.

I would create a module with the following code:

<?php
/**
 * Implementation of hook_form_alter().
 */
function custommodule_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  // All node forms are built with the form_id "<machine_name>_node_form"
  if (substr($form_id, -10) != '_node_form') {
    // Only making changes on the node forms.
    return;
  }

  // Make the menu field invisible to those without the administrator role.
  // This will hide the menu field from users with the user permissions to make changes.
  // Remember 'administrator' is not a default role in Drupal. It's one you create yourself or install a module (like Admin Role*)
  $form['menu']['#access'] = in_array('administrator', array_values($user->roles));

  // This approach allows me to tie access to any permission I care to name.
  // This specifically limits the menu field to menu administrators.
  $form['menu']['#access'] = user_access('administer menu');
}
?>

Using this approach, the form will simply not build those elements that the current user cannot access.

If you want to learn about the form elements of your node form page, you might find a guide via Google. If you are willing to slog through a full print out of the Form structure, stick drupal_set_message(print_r($form, TRUE)); in your hook_form_alter() implementation to see what's there. Even better, install the Devel , and then you can get a much nicer themed output by inserting dpm($form); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM