function field_permission_example_field_access

Implements hook_field_access().

We want to make sure that fields aren't being seen or edited by those who shouldn't.

We have to build a permission string similar to those in hook_permission() in order to ask Drupal whether the user has that permission. Permission strings will end up being like 'view any fieldnote' or 'edit own fieldnote'.

The tricky thing here is that a field can be attached to any type of entity, so it's not always trivial to figure out whether $account 'owns' the entity. We'll support access restrictions for user and node entity types, and be permissive with others, since that's easy to demonstrate.

See also

field_permission_example_permissions()

Related topics

File

field_permission_example/field_permission_example.module, line 125

Code

function field_permission_example_field_access($op, $field, $entity_type, $entity, $account) {
    // This hook will be invoked for every field type, so we have to
    // check that it's the one we're interested in.
    if ($field['type'] == 'field_permission_example_fieldnote') {
        // First we'll check if the user has the 'superuser'
        // permissions that node provides. This way administrators
        // will be able to administer the content types.
        if (user_access('bypass node access', $account)) {
            drupal_set_message(t('User can bypass node access.'));
            return TRUE;
        }
        if (user_access('administer content types', $account)) {
            drupal_set_message(t('User can administer content types.'));
            return TRUE;
        }
        // Now check for our own permissions.
        // $context will end up being either 'any' or 'own.'
        $context = 'any';
        switch ($entity_type) {
            case 'user':
            case 'node':
                // While administering the field itself, $entity will be
                // NULL, so we have to check it.
                if ($entity) {
                    if ($entity->uid == $account->uid) {
                        $context = 'own';
                    }
                }
        }
        // Assemble a permission string, such as
        // 'view any fieldnote'
        $permission = $op . ' ' . $context . ' fieldnote';
        // Finally, ask Drupal if this account has that permission.
        $access = user_access($permission, $account);
        $status = 'FALSE';
        if ($access) {
            $status = 'TRUE';
        }
        drupal_set_message($permission . ': ' . $status);
        return $access;
    }
    // We have no opinion on field types other than our own.
    return TRUE;
}