2
votes

In Drupal 7 is there a way to restrict the content of a field list based on the user role?

For example:

for user role 1, I want the custom field list to show:

Apple Banana Grape Orange

for user role 2, I want the custom field list to show:

Apple Grape

The Field Permissions module lets you restrict access to display and edit the list based on role but I'm looking for something more granular to restrict access to items in the list based on role.

2
you could use drupal.org/project/references and use its inbuild function to display a view, which prints out the options. inside the view, then, add a conditional for the users role. let me know if that kind of works and you need more help. - alex
Alex, I have references installed and I know how to build a view but I'm pretty lost on the rest of your explanation. - John81
indeed, I have to apologize, I thought that would easily be possible, but it isn't! however, a pretty hackish way would be to create a content type with a title and a list of user roles, and for every option create a node of that content type. then, in views, only show that content type. next, you have to edit the view templates (in the view: Advanced>Theme>Information). there, check whether the current user (global $user) has the corresponding role, and then print out the row. but there should be a far better way. maybe searching for a user permission taxonomy module? or the rules module? - alex

2 Answers

2
votes

You can implement hook_field_widget_form_alter() in your own module and remove certain options based on whatever criteria you'd like. For example:

function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field_name'] == 'field_MY_FIELD') {
    // Users without the "administer nodes" permission should not see the
    // "Banana" and "Orange" options.
    if (!user_access('administer nodes')) {
      unset($element['#options']['banana'], $element['#options']['orange']);
    }
  }
}

See http://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_widget_form_alter/7 for more information on hook_field_widget_form_alter().

0
votes

We can do it without any custom module simply, by use of reference view as mentioned by alex. What is required is "to select current user as filter".

Prepare a content type user_category where you save the user name against the category, eg

user: 1 - category: - apple, grape, banana
user 2 - category: apple, grape etc

Form a view of type reference and filter as current user and you are done.

Use field type as reference in the content, select the view in field options.