field_test.field.inc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * @file
  4. * Defines a field type and its formatters and widgets.
  5. */
  6. use Drupal\Core\Entity\FieldableEntityInterface;
  7. use Drupal\Core\Access\AccessResult;
  8. use Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException;
  9. use Drupal\Core\Field\FieldDefinitionInterface;
  10. use Drupal\Core\Field\FieldItemListInterface;
  11. use Drupal\Core\Session\AccountInterface;
  12. use Drupal\field\FieldStorageConfigInterface;
  13. /**
  14. * Implements hook_field_widget_info_alter().
  15. */
  16. function field_test_field_widget_info_alter(&$info) {
  17. $info['test_field_widget_multiple']['field_types'][] = 'test_field';
  18. $info['test_field_widget_multiple']['field_types'][] = 'test_field_with_preconfigured_options';
  19. // Add extra widget when needed for tests.
  20. // @see \Drupal\field\Tests\FormTest::widgetAlterTest().
  21. if ($alter_info = \Drupal::state()->get("field_test.widget_alter_test")) {
  22. if ($alter_info['widget'] === 'test_field_widget_multiple_single_value') {
  23. $info['test_field_widget_multiple_single_value']['field_types'][] = 'test_field';
  24. }
  25. }
  26. }
  27. /**
  28. * Implements hook_field_storage_config_update_forbid().
  29. */
  30. function field_test_field_storage_config_update_forbid(FieldStorageConfigInterface $field_storage, FieldStorageConfigInterface $prior_field_storage) {
  31. if ($field_storage->getType() == 'test_field' && $field_storage->getSetting('unchangeable') != $prior_field_storage->getSetting('unchangeable')) {
  32. throw new FieldStorageDefinitionUpdateForbiddenException("field_test 'unchangeable' setting cannot be changed'");
  33. }
  34. }
  35. /**
  36. * Sample 'default value' callback.
  37. */
  38. function field_test_default_value(FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
  39. return [['value' => 99]];
  40. }
  41. /**
  42. * Implements hook_entity_field_access().
  43. */
  44. function field_test_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  45. if ($field_definition->getName() == "field_no_{$operation}_access") {
  46. return AccessResult::forbidden();
  47. }
  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();
  52. }
  53. return AccessResult::allowed();
  54. }