You are here

public static function PeriodEntityTrait::periodBaseFieldDefinitions in Recurring Time Period 8

Returns an array of base field definitions for representing a time period.

Parameters

\Drupal\Core\Entity\EntityTypeInterface $entity_type: The entity type to add the period fields to.

Return value

\Drupal\Core\Field\BaseFieldDefinition[] An array of base field definitions.

Throws

\Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException Thrown when the entity type does not implement PeriodEntityInterface or if it does not the necessary entity keys.

File

src/Entity/PeriodEntityTrait.php, line 92

Class

PeriodEntityTrait
Provides base fields and accessors for entities that represent a time period.

Namespace

Drupal\recurring_period\Entity

Code

public static function periodBaseFieldDefinitions(EntityTypeInterface $entity_type) {
  if (!is_subclass_of($entity_type
    ->getClass(), PeriodEntityInterface::class)) {
    throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type
      ->id() . ' does not implement \\Drupal\\recurring_period\\Entity\\PeriodEntityInterface.');
  }
  if ($entity_type
    ->hasKey('date_range')) {
    return [
      $entity_type
        ->getKey('date_range') => BaseFieldDefinition::create('daterange')
        ->setLabel(new TranslatableMarkup('Period date'))
        ->setRevisionable(TRUE)
        ->setDefaultValue(TRUE)
        ->setDisplayOptions("view", [
        'type' => "daterange_default",
        'weight' => "5",
      ])
        ->setDisplayConfigurable("view", TRUE)
        ->setDisplayOptions("form", [
        'type' => "daterange_default",
        'weight' => "5",
      ])
        ->setDisplayConfigurable("form", TRUE),
    ];
  }
  elseif ($entity_type
    ->hasKey('start_date') && $entity_type
    ->hasKey('end_date')) {
    return [
      $entity_type
        ->getKey('start_date') => BaseFieldDefinition::create('date')
        ->setLabel(new TranslatableMarkup('Period start date'))
        ->setRevisionable(TRUE)
        ->setDefaultValue(TRUE)
        ->setDisplayConfigurable("view", TRUE)
        ->setDisplayConfigurable("form", TRUE),
      $entity_type
        ->getKey('end_date') => BaseFieldDefinition::create('date')
        ->setLabel(new TranslatableMarkup('Period end date'))
        ->setRevisionable(TRUE)
        ->setDefaultValue(TRUE)
        ->setDisplayConfigurable("view", TRUE)
        ->setDisplayConfigurable("form", TRUE),
    ];
  }
  else {
    throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type
      ->id() . ' does not have either a "date_range" or "start_date" and "end_date" entity keys.');
  }
}