7.x field.module field_access($op, $field, $entity_type, $entity = NULL, $account = NULL)

Determine whether the user has access to a given field.

This function does not determine whether access is granted to the entity itself, only the specific field. Callers are responsible for ensuring that entity access is also respected. For example, when checking field access for nodes, check node_access() before checking field_access(), and when checking field access for entities using the Entity API contributed module, check entity_access() before checking field_access().

Parameters

$op: The operation to be performed. Possible values:

  • 'edit'
  • 'view'

$field: The full field structure array for the field on which the operation is to be performed. See field_info_field().

$entity_type: The type of $entity; e.g., 'node' or 'user'.

$entity: (optional) The entity for the operation.

$account: (optional) The account to check, if not given use currently logged in user.

Return value

TRUE if the operation is allowed; FALSE if the operation is denied.

Related topics

3 calls to field_access()
field_default_form in modules/field/field.form.inc
Creates a form element for a field and can populate it with a default value.
field_default_view in modules/field/field.default.inc
Builds a renderable array for one field on one entity instance.
file_file_download in modules/file/file.module
Implements hook_file_download().

File

modules/field/field.module, line 997
Attach custom data fields to Drupal entities.

Code

function field_access($op, $field, $entity_type, $entity = NULL, $account = NULL) {
  global $user;

  if (!isset($account)) {
    $account = $user;
  }

  foreach (module_implements('field_access') as $module) {
    $function = $module . '_field_access';
    $access = $function($op, $field, $entity_type, $entity, $account);
    if ($access === FALSE) {
      return FALSE;
    }
  }
  return TRUE;
}

Comments

Dave Reid’s picture

You cannot rely solely on this function to see if the user can do something with a certain field, you must also be sure to check if the user can also access the entity itself. For nodes, you can use node_access($op, $node, $account). For other entities it's a little more challenging. If you have the Entity API module you can use the entity_access($op, $entity_type, $entity, $account) function.