1

How do I programmatically set role based permissions on a field?

For example, I have field_my_field, for which I want the following permissions:

  • Owner can view and edit
  • Role X can view and edit
  • Role Y can view only

Looking in the database, the role_permissions table looks like it's what contains the data, but I'm confused about the actual permissions, as they're very close to natural language. e.g. 'access site in maintenance mode' although field ones make more sense:

  • Edit own field_my_field (owner can edit)
  • View own field_my_field (owner can view)
  • Edit field_my_field (can edit any)

I guess it's something along the lines of granting the permission to a RID, and identifying the module which interprets the permission.

Note: I'm trying to do this in another module with PHP - not in the UI. The Field Permissions module is great, but I need to do this in my code.

  • I'm trying to do this in another module with PHP - not in the UI. Yup, the Field Permissions module is great, but I need to do this in my code. Drupal 7 – Simo Nov 30 '16 at 22:54
1

Ok, worked this one out...

I created my own function to do this, which I have called in the MY_MODULE.install file, as I'm creating the fields there, and as I understand, you can't set permissions in the install file.

Note, this is just a custom function name, not a hook - you could call it anything.

function MY_MODULE_assign_field_permissions($role_name, $permission, $field_name) {
    $permissions = array($permission.' '.$field_name)
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
}

$role_name is the name of your role, $permission is the natural language permission, like 'view own', 'create', 'edit', etc. and finally $field_name is the name you gave your field.

Here's how I would call it in my MY_MODULE.install file to allow the role type my_role view their own entries for field_my_field:

MY_MODULE_assign_field_permissions('my_role', 'view own', 'field_my_field');
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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