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';
22 // Add extra widget when needed for tests.
23 // @see \Drupal\field\Tests\FormTest::widgetAlterTest().
24 if ($alter_info = \Drupal::state()->get("field_test.widget_alter_test")) {
25 if ($alter_info['widget'] === 'test_field_widget_multiple_single_value') {
26 $info['test_field_widget_multiple_single_value']['field_types'][] = 'test_field';
32 * Implements hook_field_storage_config_update_forbid().
34 function field_test_field_storage_config_update_forbid(FieldStorageConfigInterface $field_storage, FieldStorageConfigInterface $prior_field_storage) {
35 if ($field_storage->getType() == 'test_field' && $field_storage->getSetting('unchangeable') != $prior_field_storage->getSetting('unchangeable')) {
36 throw new FieldStorageDefinitionUpdateForbiddenException("field_test 'unchangeable' setting cannot be changed'");
41 * Sample 'default value' callback.
43 function field_test_default_value(FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
44 return [['value' => 99]];
48 * Implements hook_entity_field_access().
50 function field_test_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
51 if ($field_definition->getName() == "field_no_{$operation}_access") {
52 return AccessResult::forbidden();
55 // Only grant view access to test_view_field fields when the user has
56 // 'view test_view_field content' permission.
57 if ($field_definition->getName() == 'test_view_field' && $operation == 'view') {
58 return AccessResult::forbiddenIf(!$account->hasPermission('view test_view_field content'))->cachePerPermissions();
61 return AccessResult::allowed();