5 * Defines a field type and its formatters and widgets.
8 use Drupal\Core\Entity\FieldableEntityInterface;
9 use Drupal\Core\Access\AccessResult;
10 use Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException;
11 use Drupal\Core\Field\FieldDefinitionInterface;
12 use Drupal\Core\Field\FieldItemListInterface;
13 use Drupal\Core\Session\AccountInterface;
14 use Drupal\field\FieldStorageConfigInterface;
17 * Implements hook_field_widget_info_alter().
19 function field_test_field_widget_info_alter(&$info) {
20 $info['test_field_widget_multiple']['field_types'][] = 'test_field';
21 $info['test_field_widget_multiple']['field_types'][] = 'test_field_with_preconfigured_options';
25 * Implements hook_field_storage_config_update_forbid().
27 function field_test_field_storage_config_update_forbid(FieldStorageConfigInterface $field_storage, FieldStorageConfigInterface $prior_field_storage) {
28 if ($field_storage->getType() == 'test_field' && $field_storage->getSetting('unchangeable') != $prior_field_storage->getSetting('unchangeable')) {
29 throw new FieldStorageDefinitionUpdateForbiddenException("field_test 'unchangeable' setting cannot be changed'");
34 * Sample 'default value' callback.
36 function field_test_default_value(FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
37 return [['value' => 99]];
41 * Implements hook_entity_field_access().
43 function field_test_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
44 if ($field_definition->getName() == "field_no_{$operation}_access") {
45 return AccessResult::forbidden();
48 // Only grant view access to test_view_field fields when the user has
49 // 'view test_view_field content' permission.
50 if ($field_definition->getName() == 'test_view_field' && $operation == 'view') {
51 return AccessResult::forbiddenIf(!$account->hasPermission('view test_view_field content'))->cachePerPermissions();
54 return AccessResult::allowed();