You are here

function relation_add_endpoint_field in Relation 8

Same name and namespace in other branches
  1. 8.2 relation.module \relation_add_endpoint_field()

Adds an endpoint field to a relation type.

1 call to relation_add_endpoint_field()
RelationType::postSave in src/Entity/RelationType.php
Acts on a saved entity before the insert or update hook is invoked.

File

./relation.module, line 309
Describes relations between entities.

Code

function relation_add_endpoint_field(RelationTypeInterface $relation_type) {
  $field = FieldStorageConfig::loadByName('relation', RELATION_FIELD_NAME);
  $instance = FieldConfig::loadByName('relation', $relation_type
    ->id(), RELATION_FIELD_NAME);
  if (empty($field)) {
    $field = FieldStorageConfig::create(array(
      'field_name' => RELATION_FIELD_NAME,
      'entity_type' => 'relation',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
      'type' => 'relation_endpoint',
      'locked' => TRUE,
    ));
    $field
      ->save();
  }
  if ($field && empty($instance)) {

    // Attach field instance.
    $instance = FieldConfig::create(array(
      'field_storage' => $field,
      'bundle' => $relation_type
        ->id(),
      'label' => t('Endpoints'),
      'settings' => array(),
    ));
    $instance
      ->save();

    // Widget settings.
    $entity_form_display = \Drupal::entityTypeManager()
      ->getStorage('entity_form_display')
      ->load('relation.' . $relation_type
      ->id() . '.default');
    if (!$entity_form_display) {
      $entity_form_display = EntityFormDisplay::create(array(
        'targetEntityType' => 'relation',
        'bundle' => $relation_type
          ->id(),
        'mode' => 'default',
        'status' => TRUE,
      ));
    }
    $entity_form_display
      ->setComponent(RELATION_FIELD_NAME, array(
      'type' => 'relation_endpoint',
    ))
      ->save();

    // Display settings.
    $display = \Drupal::entityTypeManager()
      ->getStorage('entity_view_display')
      ->load('relation.' . $relation_type
      ->id() . '.default');
    if (!$display) {
      $display = EntityViewDisplay::create(array(
        'targetEntityType' => 'relation',
        'bundle' => $relation_type
          ->id(),
        'mode' => 'default',
        'status' => TRUE,
      ));
    }
    $display
      ->setComponent(RELATION_FIELD_NAME, array(
      'label' => 'hidden',
      'type' => 'relation_endpoint',
    ))
      ->save();
  }
}