FieldAPIHandlerTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Drupal\views;
  3. use Drupal\Core\Field\BaseFieldDefinition;
  4. /**
  5. * A trait containing helper methods for field definitions.
  6. */
  7. trait FieldAPIHandlerTrait {
  8. /**
  9. * The field definition.
  10. *
  11. * @var \Drupal\Core\Field\FieldDefinitionInterface
  12. */
  13. protected $fieldDefinition;
  14. /**
  15. * The field storage definition.
  16. *
  17. * @var \Drupal\field\FieldStorageConfigInterface
  18. */
  19. protected $fieldStorageDefinition;
  20. /**
  21. * Gets the field definition.
  22. *
  23. * A View works on an entity type across bundles, and thus only has access to
  24. * field storage definitions. In order to be able to use widgets and
  25. * formatters, we create a generic field definition out of that storage
  26. * definition.
  27. *
  28. * @see BaseFieldDefinition::createFromFieldStorageDefinition()
  29. *
  30. * @return \Drupal\Core\Field\FieldDefinitionInterface
  31. * The field definition used by this handler.
  32. */
  33. protected function getFieldDefinition() {
  34. if (!$this->fieldDefinition) {
  35. $field_storage_config = $this->getFieldStorageDefinition();
  36. $this->fieldDefinition = BaseFieldDefinition::createFromFieldStorageDefinition($field_storage_config);
  37. }
  38. return $this->fieldDefinition;
  39. }
  40. /**
  41. * Gets the field storage configuration.
  42. *
  43. * @return \Drupal\field\FieldStorageConfigInterface
  44. * The field storage definition used by this handler
  45. */
  46. protected function getFieldStorageDefinition() {
  47. if (!$this->fieldStorageDefinition) {
  48. $field_storage_definitions = $this->getEntityManager()->getFieldStorageDefinitions($this->definition['entity_type']);
  49. $this->fieldStorageDefinition = $field_storage_definitions[$this->definition['field_name']];
  50. }
  51. return $this->fieldStorageDefinition;
  52. }
  53. /**
  54. * Returns the entity manager.
  55. *
  56. * @return \Drupal\Core\Entity\EntityManagerInterface
  57. * The entity manager service.
  58. */
  59. protected function getEntityManager() {
  60. if (!isset($this->entityManager)) {
  61. $this->entityManager = \Drupal::entityManager();
  62. }
  63. return $this->entityManager;
  64. }
  65. }