diff --git a/core/config/schema/core.data_types.schema.yml b/core/config/schema/core.data_types.schema.yml
index 0c9ad70..113549b 100644
--- a/core/config/schema/core.data_types.schema.yml
+++ b/core/config/schema/core.data_types.schema.yml
@@ -580,6 +580,50 @@ field.value.entity_reference:
       type: string
       label: 'Target UUID'
 
+# Schema for the configuration of the Entity reference field type.
+
+field.storage_settings.dynamic_entity_reference:
+  type: mapping
+  label: 'Dynamic entity reference settings'
+  mapping:
+    target_type:
+      type: string
+      label: 'Type of item to reference'
+    exclude_entity_types:
+      type: boolean
+      label: 'Exclude the selected items'
+    entity_type_ids:
+      type: sequence
+      label: 'Entity Type IDs'
+      sequence:
+        - type: string
+          label: 'Entity Type ID'
+
+field.field_settings.dynamic_entity_reference:
+  type: sequence
+  label: 'Dynamic entity reference settings'
+  sequence:
+    - type: mapping
+      label: 'Entity Type ID'
+      mapping:
+        handler:
+          type: string
+          label: 'Reference method'
+        handler_settings:
+          type: entity_reference.[%parent.handler].handler_settings
+          label: 'Reference method settings'
+
+field.value.dynamic_entity_reference:
+  type: mapping
+  label: 'Default value'
+  mapping:
+    target_id:
+      type: string
+      label: 'Entity ID'
+    target_type:
+      type: string
+      label: 'Type of item to reference'
+
 # Schema for the configuration of the Boolean field type.
 
 field.storage_settings.boolean:
diff --git a/core/config/schema/core.entity.schema.yml b/core/config/schema/core.entity.schema.yml
index 4afb536..38ad835 100644
--- a/core/config/schema/core.entity.schema.yml
+++ b/core/config/schema/core.entity.schema.yml
@@ -294,4 +294,3 @@ field.formatter.settings.entity_reference_label:
     link:
       type: boolean
       label: 'Link label to the referenced entity'
-
diff --git a/core/lib/Drupal/Core/Field/DataDynamicReferenceDefinition.php b/core/lib/Drupal/Core/Field/DataDynamicReferenceDefinition.php
new file mode 100644
index 0000000..9ae150f
--- /dev/null
+++ b/core/lib/Drupal/Core/Field/DataDynamicReferenceDefinition.php
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Field\DataDynamicReferenceDefinition.
+ */
+
+namespace Drupal\Core\Field;
+
+use Drupal\Core\TypedData\DataReferenceDefinition;
+
+/**
+ * A typed data definition class for defining dynamic references.
+ *
+ * This is different from the base class in that the entity type being
+ * referenced is part of the data, rather than being a setting.
+ */
+class DataDynamicReferenceDefinition extends DataReferenceDefinition {
+
+  /**
+   * @var \Drupal\Core\TypedData\DataDefinitionInterface
+   */
+  protected $targetDefinition;
+
+  /**
+   * Creates a new data reference definition.
+   *
+   * @param string $target_data_type
+   *   The data type of the referenced data.
+   *
+   * @return $this
+   */
+  public static function create($target_data_type) {
+    $definition['type'] = 'dynamic_' . $target_data_type . '_reference';
+    /** @var \Drupal\Core\TypedData\DataReferenceDefinition $definition */
+    $definition = new static($definition);
+    return $definition->setTargetDefinition(\Drupal::typedDataManager()->createDataDefinition($target_data_type));
+  }
+
+}
diff --git a/core/lib/Drupal/Core/Field/DynamicEntityReferenceFieldItemList.php b/core/lib/Drupal/Core/Field/DynamicEntityReferenceFieldItemList.php
new file mode 100644
index 0000000..ba7d15b
--- /dev/null
+++ b/core/lib/Drupal/Core/Field/DynamicEntityReferenceFieldItemList.php
@@ -0,0 +1,139 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Field\DynamicEntityReferenceFieldItemList.
+ */
+
+namespace Drupal\Core\Field;
+
+use Drupal\Core\Entity\FieldableEntityInterface;
+use Drupal\Core\Form\FormStateInterface;
+
+/**
+ * Defines a item list class for dynamic entity reference fields.
+ *
+ * This is different from the base class in that the entity type being
+ * referenced is part of the field data, rather than being a setting.
+ */
+class DynamicEntityReferenceFieldItemList extends EntityReferenceFieldItemList {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function referencedEntities() {
+    if (empty($this->list)) {
+      return [];
+    }
+
+    // Collect the IDs of existing entities to load, and directly grab the
+    // "autocreate" entities that are already populated in $item->entity.
+    $target_entities = $ids = [];
+    foreach ($this->list as $delta => $item) {
+      if ($item->hasNewEntity()) {
+        $target_entities[$delta] = $item->entity;
+      }
+      elseif ($item->target_id !== NULL) {
+        $ids[$item->target_type][$delta] = $item->target_id;
+      }
+    }
+
+    // Load and add the existing entities.
+    if ($ids) {
+      foreach ($ids as $target_type => $entity_type_ids) {
+        $entities = \Drupal::entityManager()
+          ->getStorage($target_type)
+          ->loadMultiple($entity_type_ids);
+        foreach ($ids as $delta => $target_id) {
+          if (isset($entities[$target_id])) {
+            $target_entities[$delta] = $entities[$target_id];
+          }
+        }
+      }
+      // Ensure the returned array is ordered by deltas.
+      ksort($target_entities);
+    }
+
+    return $target_entities;
+  }
+
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
+    // We want to bypass the EntityReferenceItem::processDefaultValue()
+    $default_value = FieldItemList::processDefaultValue($default_value, $entity, $definition);
+
+    if ($default_value) {
+      // Convert UUIDs to numeric IDs.
+      $all_uuids = [];
+      foreach ($default_value as $delta => $properties) {
+        if (isset($properties['target_uuid'])) {
+          $target_type = $properties['target_type'];
+          $all_uuids[$target_type][$delta] = $properties['target_uuid'];
+        }
+      }
+      $entity_uuids = [];
+      foreach ($all_uuids as $target_type => $uuids) {
+        if ($uuids) {
+          $entity_ids = \Drupal::entityQuery($target_type)
+            ->condition('uuid', $uuids, 'IN')
+            ->execute();
+          $entities = \Drupal::entityManager()
+            ->getStorage($target_type)
+            ->loadMultiple($entity_ids);
+          $entity_uuids[$target_type] = [];
+          foreach ($entities as $id => $entity) {
+            $entity_uuids[$target_type][$entity->uuid()] = $id;
+          }
+          foreach ($uuids as $delta => $uuid) {
+            if (isset($entity_uuids[$uuid])) {
+              $default_value[$delta]['target_id'] = $entity_uuids[$target_type][$uuid];
+              $default_value[$delta]['target_type'] = $target_type;
+              unset($default_value[$delta]['target_uuid']);
+            }
+            else {
+              unset($default_value[$delta]);
+            }
+          }
+        }
+      }
+
+      // Ensure we return consecutive deltas, in case we removed unknown UUIDs.
+      $default_value = array_values($default_value);
+    }
+    return $default_value;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {
+    // We can not call EntityReferenceItem::defaultValuesFormSubmit(), so
+    // copy the code from FieldItemList::defaultValuesFormSubmit(). Extracts
+    // the submitted value as an array.
+    $widget = $this->defaultValueWidget($form_state);
+    $widget->extractFormValues($this, $element, $form_state);
+    $default_value = $this->getValue();
+
+    // Convert numeric IDs to UUIDs to ensure config deployability.
+    $all_ids = [];
+    foreach ($default_value as $delta => $properties) {
+      $all_ids[$properties['target_type']][] = $properties['target_id'];
+    }
+    $entities = [];
+    foreach ($all_ids as $target_type => $ids) {
+      $entities[$target_type] = \Drupal::entityManager()
+        ->getStorage($target_type)
+        ->loadMultiple($ids);
+    }
+
+    foreach ($default_value as $delta => $properties) {
+      unset($default_value[$delta]['target_id']);
+      $default_value[$delta]['target_uuid'] = $entities[$properties['target_type']][$properties['target_id']]->uuid();
+    }
+    return $default_value;
+  }
+
+}
diff --git a/core/lib/Drupal/Core/Field/Plugin/DataType/DynamicEntityReference.php b/core/lib/Drupal/Core/Field/Plugin/DataType/DynamicEntityReference.php
new file mode 100644
index 0000000..a383a9e
--- /dev/null
+++ b/core/lib/Drupal/Core/Field/Plugin/DataType/DynamicEntityReference.php
@@ -0,0 +1,48 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Field\Plugin\DataType\DynamicEntityReference.
+ */
+
+namespace Drupal\Core\Field\Plugin\DataType;
+
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\Entity\Plugin\DataType\EntityReference;
+
+/**
+ * Defines a 'dynamic_entity_reference' data type.
+ *
+ * This serves as 'dynamic_entity' property of entity reference field items and
+ * gets its value set from the parent.
+ *
+ * @code
+ * $definition = \Drupal\Core\Entity\EntityDefinition::create($entity_type)
+ *   ->addConstraint('Bundle', $bundle);
+ * \Drupal\Core\TypedData\DataReferenceDefinition::create('dynamic_entity')
+ *   ->setTargetDefinition($definition);
+ * @endcode
+ *
+ * @DataType(
+ *   id = "dynamic_entity_reference",
+ *   label = @Translation("Dynamic entity reference"),
+ *   definition_class = "\Drupal\Core\Field\DataDynamicReferenceDefinition"
+ * )
+ */
+class DynamicEntityReference extends EntityReference {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTarget() {
+    if (!isset($this->target) && isset($this->id)) {
+      // If we have a valid reference, return the entity object which is typed
+      // data itself.
+      $target_type = $this->parent->getValue()['target_type'];
+      $entity = \Drupal::entityManager()->getStorage($target_type)->load($this->id);
+      $this->target = isset($entity) ? $entity->getTypedData() : NULL;
+    }
+    return $this->target;
+  }
+
+}
diff --git a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DynamicEntityReferenceItem.php b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DynamicEntityReferenceItem.php
new file mode 100644
index 0000000..6f8ca1e
--- /dev/null
+++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DynamicEntityReferenceItem.php
@@ -0,0 +1,252 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\Field\Plugin\Field\FieldType\DynamicEntityReferenceItem.
+ */
+
+namespace Drupal\Core\Field\Plugin\Field\FieldType;
+
+use Drupal\Core\Config\Entity\ConfigEntityType;
+use Drupal\Core\Entity\EntityTypeInterface;
+use Drupal\Core\Field\FieldDefinitionInterface;
+use Drupal\Core\Field\FieldItemBase;
+use Drupal\Core\Field\FieldStorageDefinitionInterface;
+use Drupal\Core\TypedData\DataDefinition;
+use Drupal\Core\Field\DataDynamicReferenceDefinition;
+
+/**
+ * Defines the 'dynamic_entity_reference' entity field type.
+ *
+ * Supported settings (below the definition's 'settings' key) are:
+ * - exclude_entity_types: If TRUE, exclude entity the types from the list. If
+ *   FALSE, only allow those entities types in the list.
+ * - entity_type_ids: The entity type ids that can or cannot be referenced.
+ *
+ * @FieldType(
+ *   id = "dynamic_entity_reference",
+ *   label = @Translation("Dynamic entity reference"),
+ *   description = @Translation("An entity field containing a dynamic entity reference."),
+ *   no_ui = TRUE,
+ *   list_class = "\Drupal\Core\Field\DynamicEntityReferenceFieldItemList",
+ *   constraints = {"ValidReference" = {}}
+ * )
+ */
+class DynamicEntityReferenceItem extends EntityReferenceItem {
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function defaultStorageSettings() {
+    return array(
+      'exclude_entity_types' => TRUE,
+      'entity_type_ids' => array(),
+    );
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function defaultFieldSettings() {
+    $default_settings = array();
+    $labels = \Drupal::entityManager()->getEntityTypeLabels(TRUE);
+    $options = $labels['Content'];
+    // Field storage settings are not accessible here so we are assuming that
+    // all the entity types are referenceable by default.
+    // See https://www.drupal.org/node/2346273#comment-9385179 for more details.
+    foreach (array_keys($options) as $entity_type_id) {
+      $default_settings[$entity_type_id] = array(
+        'handler' => 'default',
+        'handler_settings' => array(),
+      );
+    }
+    return $default_settings;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
+    // Only supports content entities.
+    $properties['target_id'] = DataDefinition::create('integer')
+      ->setLabel(t('Entity ID'))
+      ->setSetting('unsigned', TRUE)
+      ->setRequired(TRUE);
+    $properties['target_type'] = DataDefinition::create('string')
+      ->setLabel(t('Target Entity Type'));
+    $properties['entity'] = DataDynamicReferenceDefinition::create('entity')
+      ->setLabel(t('Entity'))
+      ->setDescription(t('The referenced entity'))
+      // The entity object is computed out of the entity ID.
+      ->setComputed(TRUE)
+      ->setReadOnly(FALSE);
+
+    return $properties;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function mainPropertyName() {
+    return 'target_id';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function schema(FieldStorageDefinitionInterface $field_definition) {
+    $columns = array(
+      'target_id' => array(
+        'description' => 'The ID of the target entity.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+      ),
+      'target_type' => array(
+        'description' => 'The Entity Type ID of the target entity.',
+        'type' => 'varchar',
+        'length' => EntityTypeInterface::ID_MAX_LENGTH,
+      ),
+    );
+
+    $schema = array(
+      'columns' => $columns,
+      'indexes' => array(
+        'target_id' => array('target_id'),
+      ),
+    );
+
+    return $schema;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function onChange($property_name, $notify = TRUE) {
+    /* @var \Drupal\dynamic_entity_reference\Plugin\DataType\DynamicEntityReference $entity_property */
+    $entity_property = $this->get('entity');
+    if ($property_name == 'target_type' && !$entity_property->getValue()) {
+      $entity_property->getTargetDefinition()->setEntityTypeId($this->get('target_type')->getValue());
+    }
+    // Make sure that the target type and the target property stay in sync.
+    elseif ($property_name == 'entity') {
+      $this->writePropertyValue('target_type', $entity_property->getValue()->getEntityTypeId());
+    }
+    parent::onChange($property_name, $notify);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function setValue($values, $notify = TRUE) {
+    if (empty($values['target_type']) && !empty($values['target_id'])) {
+      throw new \InvalidArgumentException('No entity type was provided, value is not a valid entity.');
+    }
+    if (isset($values) && !is_array($values)) {
+      // If either a scalar or an object was passed as the value for the item,
+      // assign it to the 'entity' property since that works for both cases.
+      $this->set('entity', $values, $notify);
+    }
+    else {
+      // We have to bypass the EntityReferenceItem::setValue() here because we
+      // also want to invoke onChange for target_type.
+      FieldItemBase::setValue($values, FALSE);
+      // Support setting the field item with only one property, but make sure
+      // values stay in sync if only property is passed.
+      if (isset($values['target_id']) && !isset($values['entity'])) {
+        $this->onChange('target_type', FALSE);
+        $this->onChange('target_id', FALSE);
+      }
+      elseif (!isset($values['target_id']) && isset($values['entity'])) {
+        $this->onChange('entity', FALSE);
+      }
+      elseif (isset($values['target_id']) && isset($values['entity'])) {
+        // If both properties are passed, verify the passed values match. The
+        // only exception we allow is when we have a new entity: in this case
+        // its actual id and target_id will be different, due to the new entity
+        // marker.
+        if (($this->get('entity')->getTargetIdentifier() != $values['target_id']
+            || $this->get('entity')->getTargetDefinition()->getEntityTypeId() != $values['target_type'])) {
+          throw new \InvalidArgumentException('The target id, target type and entity passed to the dynamic entity reference item do not match.');
+        }
+      }
+      // Notify the parent if necessary.
+      if ($notify && $this->parent) {
+        $this->parent->onChange($this->getName());
+      }
+    }
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getValue($include_computed = FALSE) {
+    $values = parent::getValue($include_computed);
+    if (!empty($values['target_type'])) {
+      $this->properties['entity']->getDataDefinition()->getTargetDefinition()->setEntityTypeId($values['target_type']);
+    }
+    return $this->values;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function preSave() {
+    if ($this->hasNewEntity()) {
+      // Save the entity if it has not already been saved by some other code.
+      if ($this->entity->isNew()) {
+        $this->entity->save();
+      }
+      // Make sure the parent knows we are updating this property so it can
+      // react properly.
+      $this->target_id = $this->entity->id();
+      $this->target_type = $this->entity->getEntityTypeId();
+    }
+  }
+
+  /**
+   * Helper function to get all the entity type ids that can be referenced.
+   *
+   * @param array $settings
+   *   The settings of the field storage.
+   *
+   * @return string[]
+   *   All the entity type ids that can be referenced.
+   */
+  public static function getAllEntityTypeIds($settings) {
+    $labels = \Drupal::entityManager()->getEntityTypeLabels(TRUE);
+    $options = $labels['Content'];
+
+    if ($settings['exclude_entity_types']) {
+      $entity_type_ids = array_diff_key($options, $settings['entity_type_ids'] ?: array());
+    }
+    else {
+      $entity_type_ids = array_intersect_key($options, $settings['entity_type_ids'] ?: array());
+    }
+    return $entity_type_ids;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function calculateDependencies(FieldDefinitionInterface $field_definition) {
+    $dependencies = [];
+
+    if (is_array($field_definition->default_value) && count($field_definition->default_value)) {
+      $target_entity_types = static::getAllEntityTypeIds($field_definition->getFieldStorageDefinition()->getSettings());
+      foreach ($target_entity_types as $target_entity_type) {
+        foreach ($field_definition->default_value as $default_value) {
+          if (is_array($default_value) && isset($default_value['target_uuid'])) {
+            $entity = \Drupal::entityManager()->loadEntityByUuid($target_entity_type->id(), $default_value['target_uuid']);
+            // If the entity does not exist do not create the dependency.
+            // @see \Drupal\Core\Field\DynamicEntityReferenceFieldItemList::processDefaultValue()
+            if ($entity) {
+              $dependencies[$entity->getConfigDependencyKey()][] = $entity->getConfigDependencyName();
+            }
+          }
+        }
+      }
+    }
+    return $dependencies;
+  }
+
+}
diff --git a/core/modules/entity_reference/config/schema/entity_reference.schema.yml b/core/modules/entity_reference/config/schema/entity_reference.schema.yml
index 1ee04d1..8706515 100644
--- a/core/modules/entity_reference/config/schema/entity_reference.schema.yml
+++ b/core/modules/entity_reference/config/schema/entity_reference.schema.yml
@@ -70,3 +70,20 @@ field.widget.settings.entity_reference_autocomplete:
     placeholder:
       type: label
       label: 'Placeholder'
+
+field.widget.settings.dynamic_entity_reference_default:
+  type: mapping
+  label: 'Dynamic entity reference autocomplete display format settings'
+  mapping:
+    match_operator:
+      type: string
+      label: 'Autocomplete matching'
+    size:
+      type: integer
+      label: 'Size of textfield'
+    autocomplete_type:
+      type: string
+      label: 'Autocomplete type'
+    placeholder:
+      type: label
+      label: 'Placeholder'
diff --git a/core/modules/entity_reference/entity_reference.libraries.yml b/core/modules/entity_reference/entity_reference.libraries.yml
new file mode 100644
index 0000000..78ebbc8
--- /dev/null
+++ b/core/modules/entity_reference/entity_reference.libraries.yml
@@ -0,0 +1,8 @@
+drupal.dynamic_entity_reference_widget:
+  version: VERSION
+  js:
+    js/dynamic-entity-reference-widget.js: {}
+  dependencies:
+    - core/jquery
+    - core/drupal
+    - core/drupal.form
diff --git a/core/modules/entity_reference/entity_reference.routing.yml b/core/modules/entity_reference/entity_reference.routing.yml
index b2f73ff..2725562 100644
--- a/core/modules/entity_reference/entity_reference.routing.yml
+++ b/core/modules/entity_reference/entity_reference.routing.yml
@@ -5,3 +5,11 @@ entity_reference.autocomplete:
     entity_id: 'NULL'
   requirements:
     _access: 'TRUE'
+
+entity_reference.dynamic_entity_reference_autocomplete:
+  path: '/entity_reference/dynamic-autocomplete/{field_name}/{entity_type}/{bundle_name}/{target_type}/{entity_id}'
+  defaults:
+    _controller: '\Drupal\entity_reference\EntityReferenceController::handleDynamicAutocomplete'
+    entity_id: 'NULL'
+  requirements:
+    _access: 'TRUE'
diff --git a/core/modules/entity_reference/js/dynamic-entity-reference-widget.js b/core/modules/entity_reference/js/dynamic-entity-reference-widget.js
new file mode 100644
index 0000000..b3e246b
--- /dev/null
+++ b/core/modules/entity_reference/js/dynamic-entity-reference-widget.js
@@ -0,0 +1,53 @@
+/**
+ * @file
+ * Attaches entity-type selection behaviors to the widget form.
+ */
+
+(function ($) {
+
+  "use strict";
+
+  Drupal.behaviors.dynamicEntityReferenceWidget = {
+    attach: function (context) {
+      var $context = $(context);
+      var $selects = $context.find('select.dynamic-entity-reference-entity-type').once('dynamic-entity-reference');
+      if ($selects.length) {
+        $selects.change(function() {
+          var $select = $(this);
+          var $autocomplete = $select.parents('.container-inline').find('.form-autocomplete');
+          var basePath;
+          var entityId = $autocomplete.data('entity-id');
+          if (!(basePath = $autocomplete.data('base-autocomplete-path'))) {
+            // This is the first time this has run, copy the default value.
+            var autocompletePath = $autocomplete.attr('data-autocomplete-path');
+            entityId = autocompletePath.substring(autocompletePath.lastIndexOf('/') + 1, autocompletePath.length);
+            if ($.isNumeric(entityId)) {
+              // By default, the base path contains the default suffix, so cut
+              // that off.
+              basePath = autocompletePath.substring(0, autocompletePath.lastIndexOf('/'));
+              basePath = basePath.substring(0, basePath.lastIndexOf('/') + 1);
+
+            }
+            else {
+              entityId = null;
+              // By default, the base path contains the default suffix, so cut
+              // that off.
+              basePath = autocompletePath.substring(0, autocompletePath.lastIndexOf('/') + 1);
+            }
+            // Store for subsequent calls.
+            $autocomplete.data('base-autocomplete-path', basePath);
+            $autocomplete.data('entity-id', entityId);
+          }
+          if (entityId) {
+            $autocomplete.attr('data-autocomplete-path', basePath + $select.val() + '/' + entityId);
+          }
+          else {
+            $autocomplete.attr('data-autocomplete-path', basePath + $select.val());
+          }
+        });
+        $selects.change();
+      }
+    }
+  };
+
+})(jQuery);
diff --git a/core/modules/entity_reference/src/EntityReferenceController.php b/core/modules/entity_reference/src/EntityReferenceController.php
index afc4cc0..8b4bd3b 100644
--- a/core/modules/entity_reference/src/EntityReferenceController.php
+++ b/core/modules/entity_reference/src/EntityReferenceController.php
@@ -10,10 +10,12 @@
 use Drupal\Component\Utility\Tags;
 use Drupal\Component\Utility\Unicode;
 use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\Field\Plugin\Field\FieldType\DynamicEntityReferenceItem;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
 
 /**
  * Defines route controller for entity reference.
@@ -64,13 +66,13 @@ public static function create(ContainerInterface $container) {
    *   Defaults to ''.
    *
    * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
-   *   Throws access denied when either the field storage or field does not
-   *   exists or the user does not have access to edit the field.
+   *   When either the field is not an entity reference field or the user does
+   *   not have access to view and edit the field.
    *
    * @return \Symfony\Component\HttpFoundation\JsonResponse
    *   The matched labels as json.
    */
-  public function handleAutocomplete(Request $request, $type, $field_name, $entity_type, $bundle_name, $entity_id) {
+  public function handleAutocomplete(Request $request, $type, $field_name, $entity_type, $bundle_name, $entity_id = '') {
     $definitions = $this->entityManager()->getFieldDefinitions($entity_type, $bundle_name);
 
     if (!isset($definitions[$field_name])) {
@@ -99,4 +101,67 @@ public function handleAutocomplete(Request $request, $type, $field_name, $entity
 
     return new JsonResponse($matches);
   }
+
+  /**
+   * Autocomplete the label of an entity.
+   *
+   * @param Request $request
+   *   The request object that contains the typed tags.
+   * @param string $field_name
+   *   The name of the entity reference field.
+   * @param string $entity_type
+   *   The entity type.
+   * @param string $bundle_name
+   *   The bundle name.
+   * @param string $target_type
+   *   The target entity type ID to search for results.
+   * @param string $entity_id
+   *   (optional) The entity ID the entity reference field is attached to.
+   *   Defaults to ''.
+   *
+   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
+   *   If the field does not exist.
+   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
+   *   When either the field is not a dynamic entity reference field or the user
+   *   does not have access to view and edit the field.
+   *
+   * @return \Symfony\Component\HttpFoundation\JsonResponse
+   *   The matched labels as json.
+   */
+  public function handleDynamicAutocomplete(Request $request, $field_name, $entity_type, $bundle_name, $target_type, $entity_id) {
+    $definitions = $this->entityManager()->getFieldDefinitions($entity_type, $bundle_name);
+
+    if (!isset($definitions[$field_name])) {
+      throw new NotFoundHttpException;
+    }
+    /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
+    $field_definition = $definitions[$field_name];
+    $access_control_handler = $this->entityManager()->getAccessControlHandler($entity_type);
+    if ($field_definition->getType() != 'dynamic_entity_reference' || !$access_control_handler->fieldAccess('edit', $field_definition)) {
+      throw new AccessDeniedHttpException();
+    }
+
+    $settings = $field_definition->getSettings();
+    $target_types = DynamicEntityReferenceItem::getAllEntityTypeIds($settings);
+    if (!in_array($target_type, array_keys($target_types))) {
+      throw new AccessDeniedHttpException();
+    }
+
+    // We put the dummy value here so selection plugins can work.
+    // @todo Remove these once https://www.drupal.org/node/1959806
+    //   and https://www.drupal.org/node/2107243 are fixed.
+    $field_definition->settings['target_type'] = $target_type;
+    $field_definition->settings['handler'] = $settings[$target_type]['handler'];
+    $field_definition->settings['handler_settings'] = $settings[$target_type]['handler_settings'];
+
+    // Get the typed string, if exists from the URL.
+    $items_typed = $request->query->get('q');
+    $items_typed = Tags::explode($items_typed);
+    $last_item = Unicode::strtolower(array_pop($items_typed));
+
+    $matches = $this->entityReferenceAutocomplete->getMatches($field_definition, $entity_type, $bundle_name, $entity_id, '', $last_item);
+
+    return new JsonResponse($matches);
+  }
+
 }
diff --git a/core/modules/entity_reference/src/Plugin/Field/FieldWidget/DynamicEntityReferenceWidget.php b/core/modules/entity_reference/src/Plugin/Field/FieldWidget/DynamicEntityReferenceWidget.php
new file mode 100644
index 0000000..554b563
--- /dev/null
+++ b/core/modules/entity_reference/src/Plugin/Field/FieldWidget/DynamicEntityReferenceWidget.php
@@ -0,0 +1,208 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\Field\FieldWidget\DynamicEntityReferenceWidget.
+ */
+
+namespace Drupal\entity_reference\Plugin\Field\FieldWidget;
+
+use Drupal\Core\Field\FieldItemListInterface;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Field\Plugin\Field\FieldType\DynamicEntityReferenceItem;
+use Drupal\user\EntityOwnerInterface;
+
+/**
+ * Plugin implementation of the 'dynamic_entity_reference autocomplete' widget.
+ *
+ * @FieldWidget(
+ *   id = "dynamic_entity_reference_default",
+ *   label = @Translation("Autocomplete"),
+ *   description = @Translation("An autocomplete text field."),
+ *   field_types = {
+ *     "dynamic_entity_reference"
+ *   }
+ * )
+ */
+class DynamicEntityReferenceWidget extends AutocompleteWidget {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
+    $entity = $items->getEntity();
+    $target = $items->get($delta)->entity;
+
+    $available = DynamicEntityReferenceItem::getAllEntityTypeIds($this->getFieldSettings());
+    $cardinality = $items->getFieldDefinition()->getFieldStorageDefinition()->getCardinality();
+
+    // Prepare the autocomplete route parameters.
+    $autocomplete_route_parameters = array(
+      'field_name' => $this->fieldDefinition->getName(),
+      'entity_type' => $entity->getEntityTypeId(),
+      'bundle_name' => $entity->bundle(),
+      'target_type' => $items->get($delta)->target_type ?: key($available),
+    );
+
+    if ($entity_id = $entity->id()) {
+      $autocomplete_route_parameters['entity_id'] = $entity_id;
+    }
+
+    $element += array(
+      '#type' => 'textfield',
+      '#maxlength' => 1024,
+      '#default_value' => $target ? $target->label() . ' (' . $target->id() . ')' : '',
+      '#autocomplete_route_name' => 'entity_reference.dynamic_entity_reference_autocomplete',
+      '#autocomplete_route_parameters' => $autocomplete_route_parameters,
+      '#size' => $this->getSetting('size'),
+      '#placeholder' => $this->getSetting('placeholder'),
+      '#element_validate' => array(array($this, 'elementValidate')),
+      '#autocreate_uid' => ($entity instanceof EntityOwnerInterface) ? $entity->getOwnerId() : \Drupal::currentUser()->id(),
+      '#field_name' => $items->getName(),
+    );
+
+    $element['#title'] = $this->t('Label');
+
+    $entity_type = array(
+      '#type' => 'select',
+      '#options' => $available,
+      '#title' => $this->t('Entity type'),
+      '#default_value' => $items->get($delta)->target_type,
+      '#weight' => -50,
+      '#attributes' => array(
+        'class' => array('dynamic-entity-reference-entity-type'),
+      ),
+    );
+
+    $form_element = array(
+      '#type' => 'container',
+      '#attributes' => array(
+        'class' => array('container-inline'),
+      ),
+      'target_type' => $entity_type,
+      'target_id' => $element,
+      '#attached' => array(
+        'library' => array(
+          'entity_reference/drupal.dynamic_entity_reference_widget',
+        ),
+      ),
+    );
+    // Render field as details.
+    if ($cardinality == 1) {
+      $form_element['#type'] = 'details';
+      $form_element['#title'] = $items->getFieldDefinition()->getLabel();
+      $form_element['#open'] = TRUE;
+    }
+    return $form_element;
+  }
+
+  /**
+   * Checks whether a content entity is referenced.
+   *
+   * @param string $target_type
+   *   The value target entity type.
+   *
+   * @return bool
+   *   TRUE if a content entity is referenced.
+   */
+  protected function isContentReferenced($target_type = NULL) {
+    $target_type_info = \Drupal::entityManager()->getDefinition($target_type);
+    return $target_type_info->isSubclassOf('\Drupal\Core\Entity\ContentEntityInterface');
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function elementValidate($element, FormStateInterface $form_state, $form) {
+    // If a value was entered into the autocomplete.
+    $value = NULL;
+    if (!empty($element['#value'])) {
+      // If this is the default value of the field.
+      if ($form_state->hasValue('default_value_input')) {
+        $values = $form_state->getValue(array(
+          'default_value_input',
+          $element['#field_name'],
+          $element['#delta'],
+        ));
+      }
+      else {
+        $values = $form_state->getValue(array(
+          $element['#field_name'],
+          $element['#delta'],
+        ));
+      }
+      // Take "label (entity id)', match the id from parenthesis.
+      if ($this->isContentReferenced($values['target_type']) && preg_match("/.+\((\d+)\)/", $element['#value'], $matches)) {
+        $value = $matches[1];
+      }
+      elseif (preg_match("/.+\(([\w.]+)\)/", $element['#value'], $matches)) {
+        $value = $matches[1];
+      }
+      $auto_create = $this->getHandlerSetting('auto_create', $values['target_type']);
+      // Try to get a match from the input string when the user didn't use the
+      // autocomplete but filled in a value manually.
+      if ($value === NULL) {
+        // To use entity_reference selection_handler for this target_type we
+        // have to change these settings to entity_reference field settings.
+        // @todo Remove these once https://www.drupal.org/node/1959806
+        //   and https://www.drupal.org/node/2107243 are fixed.
+        $this->fakeFieldSettings($values['target_type']);
+        /** @var \Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface $handler */
+        $handler = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($this->fieldDefinition);
+        $value = $handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form, !$auto_create);
+      }
+      // Auto-create item. See
+      // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
+      if (!$value && $auto_create && (count($this->getHandlerSetting('target_bundles', $values['target_type'])) == 1)) {
+        $value = array(
+          'target_id' => NULL,
+          'entity' => $this->createNewEntity($element['#value'], $element['#autocreate_uid']),
+          // Keep the weight property.
+          '_weight' => $element['#weight'],
+        );
+        // Change the element['#parents'], so in form_set_value() we populate
+        // the correct key.
+        array_pop($element['#parents']);
+      }
+
+    }
+    $form_state->setValueForElement($element, $value);
+  }
+
+  /**
+   * Sets the fake field settings values.
+   *
+   * These settings are required by
+   * \Drupal\entity_reference\Plugin\Type\SelectionPluginManager to select the
+   * proper selection plugin and these settings are also used by
+   * \Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase
+   * @todo Remove these once https://www.drupal.org/node/1959806
+   *   and https://www.drupal.org/node/2107243 are fixed.
+   *
+   * @param string $entity_type_id
+   *   The id of the entity type.
+   */
+  protected function fakeFieldSettings($entity_type_id) {
+    $settings = $this->getFieldSettings();
+    $this->fieldDefinition->settings['target_type'] = $entity_type_id;
+    $this->fieldDefinition->settings['handler'] = $settings[$entity_type_id]['handler'];
+    $this->fieldDefinition->settings['handler_settings'] = $settings[$entity_type_id]['handler_settings'];
+  }
+
+  /**
+   * Returns the value of a setting for the entity reference selection handler.
+   *
+   * @param string $setting_name
+   *   The setting name.
+   * @param string $entity_type_id
+   *   The id of the entity type.
+   *
+   * @return mixed
+   *   The setting value.
+   */
+  protected function getHandlerSetting($setting_name, $entity_type_id) {
+    $settings = $this->getFieldSettings();
+    return isset($settings[$entity_type_id]['handler_settings'][$setting_name]) ? $settings[$entity_type_id]['handler_settings'][$setting_name] : NULL;
+  }
+
+}
diff --git a/core/modules/entity_reference/src/Tests/DynamicEntityReferenceIntegrationTest.php b/core/modules/entity_reference/src/Tests/DynamicEntityReferenceIntegrationTest.php
new file mode 100644
index 0000000..c12627c
--- /dev/null
+++ b/core/modules/entity_reference/src/Tests/DynamicEntityReferenceIntegrationTest.php
@@ -0,0 +1,133 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Tests\DynamicEntityReferenceIntegrationTest.
+ */
+
+namespace Drupal\entity_reference\Tests;
+
+use Drupal\Component\Utility\String;
+use Drupal\config\Tests\AssertConfigEntityImportTrait;
+use Drupal\field\Entity\FieldConfig;
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests various Dynamic Entity reference base field.
+ *
+ * @group entity_reference
+ */
+class DynamicEntityReferenceIntegrationTest extends WebTestBase {
+  use AssertConfigEntityImportTrait;
+
+  /**
+   * The entity type used in this test.
+   *
+   * @var string
+   */
+  protected $entityType = 'dynamic_entity_test';
+
+  /**
+   * The bundle used in this test.
+   *
+   * @var string
+   */
+  protected $bundle = 'dynamic_entity_test';
+
+  /**
+   * The name of the field used in this test.
+   *
+   * @var string
+   */
+  protected $fieldName;
+
+  /**
+   * The logged in user.
+   *
+   * @var \Drupal\user\UserInterface
+   */
+  protected $webUser;
+
+  /**
+   * Modules to install.
+   *
+   * @var array
+   */
+  public static $modules = array('entity_reference', 'field_ui', 'dynamic_entity_reference_test');
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    // Create a test user.
+    $this->webUser = $this->drupalCreateUser(array('administer dynamic_entity_test content'));
+    $this->drupalLogin($this->webUser);
+  }
+
+  /**
+   * Tests the dynamic entity reference base field.
+   */
+  public function testDynamicEntityTypesAndWidgets() {
+
+    $entity_name1 = $this->randomMachineName();
+    $edit = array(
+      'name[0][value]' => $entity_name1,
+      'dynamic_references[0][target_type]' => 'user',
+      'dynamic_references[0][target_id]' => $this->webUser->label() . ' (' . $this->webUser->id() . ')',
+    );
+    $this->drupalPostForm($this->entityType . '/add', $edit, t('Save'));
+    $entity1 = current(entity_load_multiple_by_properties($this->entityType, array('name' => $entity_name1)));
+    $this->assertEqual($entity1->dynamic_references->target_id, $this->webUser->id());
+    $this->assertEqual($entity1->dynamic_references->target_type, 'user');
+    $this->assertEqual($entity1->dynamic_references->entity->id(), $this->webUser->id());
+    $this->assertEqual($entity1->dynamic_references->entity->label(), $this->webUser->label());
+
+
+    $entity_name2 = $this->randomMachineName();
+    $edit = array(
+      'name[0][value]' => $entity_name2,
+      'dynamic_references[0][target_type]' => $this->entityType,
+      'dynamic_references[0][target_id]' => $entity1->label() .  ' (' . $entity1->id() . ')',
+    );
+    $this->drupalPostForm($this->entityType . '/add', $edit, t('Save'));
+
+    $entity2 = current(entity_load_multiple_by_properties($this->entityType, array('name' => $entity_name2)));
+    $this->assertEqual($entity2->dynamic_references->target_id, $entity1->id());
+    $this->assertEqual($entity2->dynamic_references->target_type, $this->entityType);
+    $this->assertEqual($entity2->dynamic_references->entity->id(), $entity1->id());
+    $this->assertEqual($entity2->dynamic_references->entity->label(), $entity1->label());
+
+    // Edit the reference to be to the user.
+    $edit = array(
+      'dynamic_references[0][target_type]' => 'user',
+      'dynamic_references[0][target_id]' => $this->webUser->label() . ' (' . $this->webUser->id() . ')',
+    );
+    $this->drupalPostForm($this->entityType . '/' . $entity2->id() . '/edit', $edit, t('Save'));
+    $entity2 = entity_load($this->entityType, $entity2->id(), TRUE);
+    $this->assertEqual($entity2->dynamic_references->target_id, $this->webUser->id());
+    $this->assertEqual($entity2->dynamic_references->target_type, 'user');
+    $this->assertEqual($entity2->dynamic_references->entity->id(), $this->webUser->id());
+    $this->assertEqual($entity2->dynamic_references->entity->label(), $this->webUser->label());
+
+
+    /*
+        // Test another input of the entity label without a ' (entity_id)' suffix.
+        $entity_name3 = $this->randomMachineName();
+        $edit = array(
+          'name[0][value]' => $entity_name3,
+          'dynamic_references[0][target_type]' => 'user',
+          'dynamic_references[0][target_id]' => $this->webUser->label(),
+        );
+        $this->drupalPostForm($this->entityType . '/add', $edit, t('Save'));
+        $entity3 = current(entity_load_multiple_by_properties($this->entityType, array('name' => $entity_name3)));
+        $this->assertEqual($entity3->dynamic_references->target_id, $this->webUser->id());
+        $this->assertEqual($entity3->dynamic_references->target_type, 'user');
+        $this->assertEqual($entity3->dynamic_references->entity->id(), $this->webUser->id());
+        $this->assertEqual($entity3->dynamic_references->entity->label(), $this->webUser->label());
+      */
+  }
+
+
+}
diff --git a/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.info.yml b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.info.yml
new file mode 100644
index 0000000..2ae82cb
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.info.yml
@@ -0,0 +1,8 @@
+name: "Dynamic Entity Reference Test"
+type: module
+description: "Support module for the Dynamic Entity Reference tests."
+core: 8.x
+package: Testing
+version: VERSION
+dependencies:
+  - entity_reference
diff --git a/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.permissions.yml b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.permissions.yml
new file mode 100644
index 0000000..f9708fa
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.permissions.yml
@@ -0,0 +1,3 @@
+administer dynamic_entity_test content:
+  title: 'Administer dynamic_entity_test content'
+  description: 'Manage dynamic_entity_test content'
diff --git a/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.routing.yml b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.routing.yml
new file mode 100644
index 0000000..6041ca0
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/dynamic_entity_reference_test.routing.yml
@@ -0,0 +1,23 @@
+entity.dynamic_entity_test.canonical:
+  path: '/dynamic_entity_test/{dynamic_entity_test}'
+  defaults:
+    _entity_view: 'dynamic_entity_test.full'
+    _title: 'Test full view mode'
+  requirements:
+    _access: 'TRUE'
+
+entity.dynamic_entity_test.edit_form:
+  path: '/dynamic_entity_test/{dynamic_entity_test}/edit'
+  defaults:
+    _title: 'Edit'
+    _entity_form: 'dynamic_entity_test.default'
+  requirements:
+    _entity_access: 'dynamic_entity_test.update'
+
+entity.dynamic_entity_test.add_form:
+  path: '/dynamic_entity_test/add'
+  defaults:
+    _title: 'Add'
+    _controller: '\Drupal\dynamic_entity_reference_test\Controller\DynamicEntityController::addForm'
+  requirements:
+    _permission: 'administer dynamic_entity_test content'
diff --git a/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/Controller/DynamicEntityController.php b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/Controller/DynamicEntityController.php
new file mode 100644
index 0000000..1c5ffb9
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/Controller/DynamicEntityController.php
@@ -0,0 +1,28 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\dynamic_entity_reference_test\Controller\DynamicEntityController.
+ */
+
+namespace Drupal\dynamic_entity_reference_test\Controller;
+
+use Drupal\Core\Controller\ControllerBase;
+
+/**
+ * Defines a route controller for a form for entity creation.
+ */
+class DynamicEntityController extends ControllerBase {
+
+  /**
+   * Provides the entity creation form.
+   *
+   * @return array
+   *   Returns the entity creation form.
+   */
+  public function addForm() {
+    $entity = $this->entityManager()->getStorage('dynamic_entity_test')->create();
+    return $this->entityFormBuilder()->getForm($entity);
+  }
+
+}
diff --git a/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/DynamicEntityTestAccessControlHandler.php b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/DynamicEntityTestAccessControlHandler.php
new file mode 100644
index 0000000..5e427cf
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/DynamicEntityTestAccessControlHandler.php
@@ -0,0 +1,43 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\entity_test\EntityTestAccessControlHandler.
+ */
+
+namespace Drupal\dynamic_entity_reference_test;
+
+use Drupal\Core\Access\AccessResult;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\Entity\EntityAccessControlHandler;
+use Drupal\Core\Session\AccountInterface;
+
+/**
+ * Defines the access control handler for the test entity type for dynamic entity references.
+ */
+class DynamicEntityTestAccessControlHandler extends EntityAccessControlHandler {
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) {
+    if ($operation === 'view') {
+      return AccessResult::allowed();
+    }
+    elseif (in_array($operation, array('update', 'delete'))) {
+      return AccessResult::allowedIfHasPermission($account, 'administer dynamic_entity_test content');
+    }
+
+    // No opinion.
+    return AccessResult::neutral();
+
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
+    return AccessResult::allowedIfHasPermission($account, 'administer dynamic_entity_test content');
+  }
+
+}
diff --git a/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/Entity/DynamicEntityTest.php b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/Entity/DynamicEntityTest.php
new file mode 100644
index 0000000..3b00556
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/dynamic_entity_reference_test/src/Entity/DynamicEntityTest.php
@@ -0,0 +1,182 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\dynamic_entity_reference_test\Entity\DynamicEntityTest.
+ */
+
+namespace Drupal\dynamic_entity_reference_test\Entity;
+
+use Drupal\Core\Entity\ContentEntityBase;
+use Drupal\Core\Entity\EntityTypeInterface;
+use Drupal\Core\Field\BaseFieldDefinition;
+use Drupal\Core\Entity\EntityStorageInterface;
+use Drupal\user\EntityOwnerInterface;
+use Drupal\user\UserInterface;
+
+/**
+ * Defines the test entity class.
+ *
+ * @ContentEntityType(
+ *   id = "dynamic_entity_test",
+ *   label = @Translation("Test entity for dynamic entity references"),
+ *   handlers = {
+ *     "access" = "Drupal\dynamic_entity_reference_test\DynamicEntityTestAccessControlHandler",
+ *     "form" = {
+ *       "default" = "Drupal\Core\Entity\ContentEntityForm",
+ *     },
+ *     "translation" = "Drupal\content_translation\ContentTranslationHandler",
+ *     "views_data" = "Drupal\views\EntityViewsData"
+ *   },
+ *   base_table = "dynamic_entity_test",
+ *   persistent_cache = FALSE,
+ *   entity_keys = {
+ *     "id" = "id",
+ *     "uuid" = "uuid",
+ *     "bundle" = "type",
+ *     "label" = "name",
+ *     "langcode" = "langcode",
+ *     "dynamic_references" = "dynamic_references",
+ *   },
+ *   links = {
+ *     "canonical" = "/dynamic_entity_test/{dynamic_entity_test}",
+ *     "edit-form" = "/dynamic_entity_test/manage/{dynamic_entity_test}",
+ *   },
+ * )
+ */
+class DynamicEntityTest extends ContentEntityBase implements EntityOwnerInterface {
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function preCreate(EntityStorageInterface $storage, array &$values) {
+    parent::preCreate($storage, $values);
+    if (empty($values['type'])) {
+      $values['type'] = $storage->getEntityTypeId();
+    }
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
+    $fields['id'] = BaseFieldDefinition::create('integer')
+      ->setLabel(t('ID'))
+      ->setDescription(t('The ID of the test entity.'))
+      ->setReadOnly(TRUE)
+      ->setSetting('unsigned', TRUE);
+
+    $fields['uuid'] = BaseFieldDefinition::create('uuid')
+      ->setLabel(t('UUID'))
+      ->setDescription(t('The UUID of the test entity.'))
+      ->setReadOnly(TRUE);
+
+    $fields['langcode'] = BaseFieldDefinition::create('language')
+      ->setLabel(t('Language code'))
+      ->setDescription(t('The language code of the test entity.'));
+
+    $fields['name'] = BaseFieldDefinition::create('string')
+      ->setLabel(t('Name'))
+      ->setDescription(t('The name of the test entity.'))
+      ->setTranslatable(TRUE)
+      ->setSetting('max_length', 32)
+      ->setDisplayOptions('view', array(
+        'label' => 'hidden',
+        'type' => 'string',
+        'weight' => -5,
+      ))
+      ->setDisplayOptions('form', array(
+        'type' => 'string_textfield',
+        'weight' => -5,
+      ));
+
+    // @todo: Add allowed values validation.
+    $fields['type'] = BaseFieldDefinition::create('string')
+      ->setLabel(t('Type'))
+      ->setDescription(t('The bundle of the test entity.'))
+      ->setRequired(TRUE);
+
+    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
+      ->setLabel(t('User ID'))
+      ->setDescription(t('The ID of the associated user.'))
+      ->setSetting('target_type', 'user')
+      ->setSetting('handler', 'default')
+      // Default EntityTest entities to have the root user as the owner, to
+      // simplify testing.
+      ->setDefaultValue(array(0 => array('target_id' => 1)))
+      ->setTranslatable(TRUE)
+      ->setDisplayOptions('form', array(
+        'type' => 'entity_reference_autocomplete',
+        'weight' => -1,
+        'settings' => array(
+          'match_operator' => 'CONTAINS',
+          'size' => '60',
+          'autocomplete_type' => 'tags',
+          'placeholder' => '',
+        ),
+      ));
+    $fields['dynamic_references'] = BaseFieldDefinition::create('dynamic_entity_reference')
+      ->setLabel(t('References'))
+      ->setDescription(t('Reference another entity.'))
+      ->setRequired(FALSE)
+      ->setDisplayOptions('form', [
+        'type' => 'dynamic_entity_reference_default',
+        'weight' => 10,
+      ]);
+
+    return $fields;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getOwner() {
+    return $this->get('user_id')->entity;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getOwnerId() {
+    return $this->get('user_id')->target_id;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function setOwnerId($uid) {
+    $this->set('user_id', $uid);
+    return $this;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function setOwner(UserInterface $account) {
+    $this->set('user_id', $account->id());
+    return $this;
+  }
+
+  /**
+   * Sets the name.
+   *
+   * @param string $name
+   *   Name of the entity.
+   *
+   * @return $this
+   */
+  public function setName($name) {
+    $this->set('name', $name);
+    return $this;
+  }
+
+  /**
+   * Returns the name.
+   *
+   * @return string
+   */
+  public function getName() {
+    return $this->get('name')->value;
+  }
+
+}
