diff --git a/core/modules/entityreference/css/entityreference-rtl.admin.css b/core/modules/entityreference/css/entityreference-rtl.admin.css
new file mode 100644
index 0000000..600e3d7
--- /dev/null
+++ b/core/modules/entityreference/css/entityreference-rtl.admin.css
@@ -0,0 +1,4 @@
+
+.entityreference-settings {
+  margin-right: 1.5em;
+}
diff --git a/core/modules/entityreference/css/entityreference.admin.css b/core/modules/entityreference/css/entityreference.admin.css
new file mode 100644
index 0000000..d6066ef
--- /dev/null
+++ b/core/modules/entityreference/css/entityreference.admin.css
@@ -0,0 +1,4 @@
+
+.entityreference-settings {
+  margin-left: 1.5em; /* LTR */
+}
diff --git a/core/modules/entityreference/entityreference.info b/core/modules/entityreference/entityreference.info
new file mode 100644
index 0000000..6437fa5
--- /dev/null
+++ b/core/modules/entityreference/entityreference.info
@@ -0,0 +1,5 @@
+name = Entity Reference
+description = Provides a field that can reference other entities.
+package = Core
+version = VERSION
+core = 8.x
diff --git a/core/modules/entityreference/entityreference.install b/core/modules/entityreference/entityreference.install
new file mode 100644
index 0000000..f655770
--- /dev/null
+++ b/core/modules/entityreference/entityreference.install
@@ -0,0 +1,41 @@
+<?php
+
+/**
+ * @file
+ * Install, update and uninstall functions for the Entity reference
+ * module.
+ */
+
+/**
+ * Implements hook_field_schema().
+ */
+function entityreference_field_schema($field) {
+  $schema = array(
+    'columns' => array(
+      'target_id' => array(
+        'description' => 'The id of the target entity.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+    ),
+    'indexes' => array(
+      'target_id' => array('target_id'),
+    ),
+    'foreign keys' => array(),
+  );
+
+  // Create a foreign key to the target entity type base type.
+  $entity_type = $field['settings']['target_type'];
+  $entity_info = entity_get_info($entity_type);
+
+  $base_table = $entity_info['base table'];
+  $id_column = $entity_info['entity keys']['id'];
+
+  $schema['foreign keys'][$base_table] = array(
+    'table' => $base_table,
+    'columns' => array('target_id' => $id_column),
+  );
+
+  return $schema;
+}
diff --git a/core/modules/entityreference/entityreference.module b/core/modules/entityreference/entityreference.module
new file mode 100644
index 0000000..d7b88ab
--- /dev/null
+++ b/core/modules/entityreference/entityreference.module
@@ -0,0 +1,406 @@
+<?php
+
+/**
+ * @file
+ * Provides a field that can reference other entities.
+ */
+
+use Symfony\Component\HttpFoundation\JsonResponse;
+
+use Drupal\Component\Utility\NestedArray;
+use Drupal\Core\Database\Query\AlterableInterface;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\entityreference\Plugin\Type\Selection\SelectionBroken;
+
+/**
+ * Implements hook_field_info().
+ */
+function entityreference_field_info() {
+  $field_info['entityreference'] = array(
+    'label' => t('Entity Reference'),
+    'description' => t('This field reference another entity.'),
+    'settings' => array(
+      // Default to the core target entity type node.
+      'target_type' => 'node',
+      // The handler for this field.
+      'handler' => 'base',
+      // The handler settings.
+      'handler_settings' => array(),
+    ),
+    'instance_settings' => array(),
+    'default_widget' => 'options_list',
+    'default_formatter' => 'entityreference_label',
+  );
+  return $field_info;
+}
+
+/**
+ * Implements hook_menu().
+ */
+function entityreference_menu() {
+  $items = array();
+
+  $items['entityreference/autocomplete/single/%/%/%'] = array(
+    'title' => 'Entity Reference Autocomplete',
+    'page callback' => 'entityreference_autocomplete_callback',
+    'page arguments' => array(2, 3, 4, 5),
+    'access callback' => 'entityreference_autocomplete_access_callback',
+    'access arguments' => array(2, 3, 4, 5),
+    'type' => MENU_CALLBACK,
+  );
+  $items['entityreference/autocomplete/tags/%/%/%'] = array(
+    'title' => 'Entity Reference Autocomplete',
+    'page callback' => 'entityreference_autocomplete_callback',
+    'page arguments' => array(2, 3, 4, 5),
+    'access callback' => 'entityreference_autocomplete_access_callback',
+    'access arguments' => array(2, 3, 4, 5),
+    'type' => MENU_CALLBACK,
+  );
+
+  return $items;
+}
+
+/**
+ * Implements hook_field_is_empty().
+ */
+function entityreference_field_is_empty($item, $field) {
+  return !isset($item['target_id']) || !is_numeric($item['target_id']);
+}
+
+/**
+ * Get the selection handler for a given entityreference field.
+ */
+function entityreference_get_selection_handler($field, $instance = NULL, EntityInterface $entity = NULL) {
+  $target_entity_type = $field['settings']['target_type'];
+
+  // Check if the entity type does exist and has a base table.
+  $entity_info = entity_get_info($target_entity_type);
+  if (empty($entity_info['base table'])) {
+    return new SelectionBroken($field, $instance, $entity);
+  }
+
+  $plugin = drupal_container()->get('plugin.manager.entityreference.selection')->getDefinition($field['settings']['handler']);
+  $class = $plugin['class'];
+
+  // Remove 'Drupal' from the entity class.
+  $class_name = '\Drupal\entityreference\Plugin\Type\Selection' . substr($entity_info['entity class'], 6);
+
+  try {
+    return new $class_name($field, $instance, $entity);
+  }
+  catch (Exception $e) {
+    return new SelectionBroken($field, $instance, $entity);
+  }
+}
+
+/**
+ * Implements hook_field_validate().
+ */
+function entityreference_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
+  $ids = array();
+  foreach ($items as $delta => $item) {
+    if (!entityreference_field_is_empty($item, $field) && $item['target_id'] !== NULL) {
+      $ids[$item['target_id']] = $delta;
+    }
+  }
+
+  if ($ids) {
+    $valid_ids = entityreference_get_selection_handler($field, $instance, $entity)->validateReferencableEntities(array_keys($ids));
+
+    $invalid_entities = array_diff_key($ids, array_flip($valid_ids));
+    if ($invalid_entities) {
+      foreach ($invalid_entities as $id => $delta) {
+        $errors[$field['field_name']][$langcode][$delta][] = array(
+          'error' => 'entityreference_invalid_entity',
+          'message' => t('The referenced entity (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id)),
+        );
+      }
+    }
+  }
+}
+
+/**
+ * Implements hook_field_settings_form().
+ *
+ * The field settings infrastructure is not AJAX enabled by default,
+ * because it doesn't pass over the $form_state.
+ * Build the whole form into a #process in which we actually have access
+ * to the form state.
+ */
+function entityreference_field_settings_form($field, $instance, $has_data) {
+  $form = array(
+    '#type' => 'container',
+    '#attached' => array(
+      'css' => array(drupal_get_path('module', 'entityreference') . '/css/entityreference.admin.css'),
+    ),
+    '#process' => array(
+      '_entityreference_field_settings_process',
+      '_entityreference_field_settings_ajax_process',
+    ),
+    '#element_validate' => array('_entityreference_field_settings_validate'),
+    '#field' => $field,
+    '#instance' => $instance,
+    '#has_data' => $has_data,
+  );
+  return $form;
+}
+
+function _entityreference_field_settings_process($form, $form_state) {
+  $field = isset($form_state['entityreference']['field']) ? $form_state['entityreference']['field'] : $form['#field'];
+  $instance = isset($form_state['entityreference']['instance']) ? $form_state['entityreference']['instance'] : $form['#instance'];
+  $has_data = $form['#has_data'];
+
+  $settings = $field['settings'];
+  $settings += array('handler' => 'base');
+
+  // Select the target entity type.
+  $entity_type_options = array();
+  foreach (entity_get_info() as $entity_type => $entity_info) {
+    $entity_type_options[$entity_type] = $entity_info['label'];
+  }
+
+  $form['target_type'] = array(
+    '#type' => 'select',
+    '#title' => t('Target type'),
+    '#options' => $entity_type_options,
+    '#default_value' => $field['settings']['target_type'],
+    '#required' => TRUE,
+    '#description' => t('The entity type that can be referenced through this field.'),
+    '#disabled' => $has_data,
+    '#size' => 1,
+    '#ajax' => TRUE,
+    '#limit_validation_errors' => array(),
+  );
+
+  $handlers = drupal_container()->get('plugin.manager.entityreference.selection')->getDefinitions();
+  $handlers_options = array();
+  foreach ($handlers as $handler => $handler_info) {
+    $handlers_options[$handler] = check_plain($handler_info['label']);
+  }
+
+  $form['handler'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Entity selection'),
+    '#tree' => TRUE,
+    '#process' => array('_entityreference_form_process_merge_parent'),
+  );
+
+  $form['handler']['handler'] = array(
+    '#type' => 'select',
+    '#title' => t('Mode'),
+    '#options' => $handlers_options,
+    '#default_value' => $settings['handler'],
+    '#required' => TRUE,
+    '#ajax' => TRUE,
+    '#limit_validation_errors' => array(),
+  );
+  $form['handler_submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Change handler'),
+    '#limit_validation_errors' => array(),
+    '#attributes' => array(
+      'class' => array('js-hide'),
+    ),
+    '#submit' => array('entityreference_settings_ajax_submit'),
+  );
+
+  $form['handler']['handler_settings'] = array(
+    '#type' => 'container',
+    '#attributes' => array('class' => array('entityreference-settings')),
+  );
+
+  $handler = entityreference_get_selection_handler($field, $instance);
+  $form['handler']['handler_settings'] += $handler->settingsForm($field, $instance);
+
+  return $form;
+}
+
+function _entityreference_field_settings_ajax_process($form, $form_state) {
+  _entityreference_field_settings_ajax_process_element($form, $form);
+  return $form;
+}
+
+function _entityreference_field_settings_ajax_process_element(&$element, $main_form) {
+  if (isset($element['#ajax']) && $element['#ajax'] === TRUE) {
+    $element['#ajax'] = array(
+      'callback' => 'entityreference_settings_ajax',
+      'wrapper' => $main_form['#id'],
+      'element' => $main_form['#array_parents'],
+    );
+  }
+
+  foreach (element_children($element) as $key) {
+    _entityreference_field_settings_ajax_process_element($element[$key], $main_form);
+  }
+}
+
+function _entityreference_form_process_merge_parent($element) {
+  $parents = $element['#parents'];
+  array_pop($parents);
+  $element['#parents'] = $parents;
+  return $element;
+}
+
+function _entityreference_element_validate_filter(&$element, &$form_state) {
+  $element['#value'] = array_filter($element['#value']);
+  form_set_value($element, $element['#value'], $form_state);
+}
+
+function _entityreference_field_settings_validate($form, &$form_state) {
+  // Store the new values in the form state.
+  $field = $form['#field'];
+  if (isset($form_state['values']['field'])) {
+    $field['settings'] = $form_state['values']['field']['settings'];
+  }
+  $form_state['entityreference']['field'] = $field;
+
+  unset($form_state['values']['field']['settings']['handler_submit']);
+}
+
+/**
+ * Ajax callback for the handler settings form.
+ *
+ * @see entityreference_field_settings_form()
+ */
+function entityreference_settings_ajax($form, $form_state) {
+  $trigger = $form_state['triggering_element'];
+  return NestedArray::getValue($form, $trigger['#ajax']['element']);
+}
+
+/**
+ * Submit handler for the non-JS case.
+ *
+ * @see entityreference_field_settings_form()
+ */
+function entityreference_settings_ajax_submit($form, &$form_state) {
+  $form_state['rebuild'] = TRUE;
+}
+
+/**
+ * Implements hook_field_widget_info_alter().
+ *
+ * @todo: Move this to plugin alteration after:
+ * http://drupal.org/node/1751234
+ * http://drupal.org/node/1705702
+ */
+function entityreference_field_widget_info_alter(array &$info) {
+  if (module_exists('options')) {
+    $info['options_select']['field types'][] = 'entityreference';
+    $info['options_buttons']['field types'][] = 'entityreference';
+  }
+}
+
+/**
+ * Implements hook_options_list().
+ */
+function entityreference_options_list($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
+  return entityreference_get_selection_handler($field, $instance, $entity)->getReferencableEntities();
+}
+
+/**
+ * Implements hook_query_TAG_alter().
+ */
+function entityreference_query_entityreference_alter(AlterableInterface $query) {
+  $handler = $query->getMetadata('entityreference_selection_handler');
+  $handler->entityFieldQueryAlter($query);
+}
+
+/**
+ * Menu Access callback for the autocomplete widget.
+ *
+ * @param string $type
+ *   The widget type (i.e. 'single' or '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.
+ *
+ * @return bool
+ *   TRUE if user can access this menu item, FALSE otherwise.
+ */
+function entityreference_autocomplete_access_callback($type, $field_name, $entity_type, $bundle_name) {
+  if (!$field = field_info_field($field_name)) {
+    return FALSE;
+  }
+  if (!$instance = field_info_instance($entity_type, $field_name, $bundle_name)){
+    return FALSE;
+  }
+
+  if ($field['type'] != 'entityreference' || !field_access('edit', $field, $entity_type)) {
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+/**
+ * Menu callback: autocomplete the label of an entity.
+ *
+ * @param string $type
+ *   The widget type (i.e. 'single' or '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 $entity_id
+ *   (optional) The entity ID the entity-reference field is attached to.
+ *   Defaults to ''.
+ * @param string $string
+ *   The label of the entity to query by.
+ */
+function entityreference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') {
+  $field = field_info_field($field_name);
+  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
+  $matches = array();
+
+  $target_type = $field['settings']['target_type'];
+
+  $entity = NULL;
+
+  if ($entity_id !== 'NULL') {
+    $entity = entity_load($entity_type, $entity_id);
+    // TODO: Improve when we have entity_access().
+    $entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE;
+    if (!$entity || !$entity_access) {
+      return MENU_ACCESS_DENIED;
+    }
+  }
+  $handler = entityreference_get_selection_handler($field, $instance, $entity);
+
+  if ($type == 'tags') {
+    // The user enters a comma-separated list of tags. We only autocomplete the last tag.
+    $tags_typed = drupal_explode_tags($string);
+    $tag_last = drupal_strtolower(array_pop($tags_typed));
+    if (!empty($tag_last)) {
+      $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
+    }
+  }
+  else {
+    // The user enters a single tag.
+    $prefix = '';
+    $tag_last = $string;
+  }
+
+  if (isset($tag_last)) {
+    // Get an array of matching entities.
+    $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10);
+
+    // Loop through the products and convert them into autocomplete output.
+    foreach ($entity_labels as $entity_id => $label) {
+      $key = "$label ($entity_id)";
+      // Strip things like starting/trailing white spaces, line breaks and tags.
+      $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
+      // Names containing commas or quotes must be wrapped in quotes.
+      if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
+        $key = '"' . str_replace('"', '""', $key) . '"';
+      }
+      $matches[$prefix . $key] = '<div class="reference-autocomplete">' . $label . '</div>';
+    }
+  }
+
+  return new JsonResponse($matches);
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/EntityReferenceRecursiveRenderingException.php b/core/modules/entityreference/lib/Drupal/entityreference/EntityReferenceRecursiveRenderingException.php
new file mode 100644
index 0000000..bd4a888
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/EntityReferenceRecursiveRenderingException.php
@@ -0,0 +1,15 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\EntityReferenceRecursiveRenderingException.
+ */
+
+namespace Drupal\entityreference;
+
+use Exception;
+
+/**
+ * Exception thrown when the entity view renderer goes into a potentially infinite loop.
+ */
+class EntityReferenceRecursiveRenderingException extends Exception {}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/EntityreferenceBundle.php b/core/modules/entityreference/lib/Drupal/entityreference/EntityreferenceBundle.php
new file mode 100644
index 0000000..b93d99a
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/EntityreferenceBundle.php
@@ -0,0 +1,25 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\EntityreferenceBundle.
+ */
+
+namespace Drupal\entityreference;
+
+use Symfony\Component\DependencyInjection\ContainerBuilder;
+use Symfony\Component\HttpKernel\Bundle\Bundle;
+
+/**
+ * Entity reference dependency injection container.
+ */
+class EntityreferenceBundle extends Bundle {
+
+  /**
+   * Overrides Symfony\Component\HttpKernel\Bundle\Bundle::build().
+   */
+  public function build(ContainerBuilder $container) {
+    // register the BlockManager class with the dependency injection container.
+    $container->register('plugin.manager.entityreference.selection', 'Drupal\entityreference\Plugin\Type\SelectionPluginManager');
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/SelectionBroken.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/SelectionBroken.php
new file mode 100644
index 0000000..a3f9e47
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/SelectionBroken.php
@@ -0,0 +1,65 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\entityreference\selection\SelectionBroken.
+ *
+ * Provide entity type specific access control of the node entity type.
+ */
+
+namespace Drupal\entityreference\Plugin\Type\Selection;
+
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\Core\Entity\EntityInterface;
+
+/**
+ * A null implementation of SelectionInterface.
+ */
+class SelectionBroken implements SelectionInterface {
+
+  protected function __construct($field, $instance) {
+    $this->field = $field;
+    $this->instance = $instance;
+  }
+
+  /**
+   * Implements SelectionInterface::settingsForm().
+   */
+  public static function settingsForm($field, $instance) {
+    $form['selection_handler'] = array(
+      '#markup' => t('The selected selection handler is broken.'),
+    );
+    return $form;
+  }
+
+  /**
+   * Implements SelectionInterface::getReferencableEntities().
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+    return array();
+  }
+
+  /**
+   * Implements SelectionInterface::countReferencableEntities().
+   */
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
+    return 0;
+  }
+
+  /**
+   * Implements SelectionInterface::validateReferencableEntities().
+   */
+  public function validateReferencableEntities(array $ids) {
+    return array();
+  }
+
+  /**
+   * Implements SelectionInterface::validateAutocompleteInput().
+   */
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form) { }
+
+  /**
+   * Implements SelectionInterface::entityFieldQueryAlter().
+   */
+  public function entityFieldQueryAlter(SelectInterface $query) { }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/SelectionInterface.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/SelectionInterface.php
new file mode 100644
index 0000000..a91919c
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/SelectionInterface.php
@@ -0,0 +1,80 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\Type\Selection\SelectionInterface.
+ */
+
+namespace Drupal\entityreference\Plugin\Type\Selection;
+
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\Database\Query\SelectInterface;
+
+/**
+ * Interface definition for field widget plugins.
+ *
+ * This interface details the methods that most plugin implementations will want
+ * to override. See Drupal\field\Plugin\Type\Selection\SelectionBaseInterface for base
+ * wrapping methods that should most likely be inherited directly from
+ * Drupal\entityreference\Plugin\Type\Selection\SelectionBase.
+ */
+interface SelectionInterface {
+
+  /**
+   * Returns a list of referencable entities.
+   *
+   * @return array
+   *   An array of referencable entities, which keys are entity ids and
+   *   values (safe HTML) labels to be displayed to the user.
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0);
+
+  /**
+   * Counts entities that are referencable by a given field.
+   */
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS');
+
+  /**
+   * Validates that entities can be referenced by this field.
+   *
+   * @return array
+   *   An array of valid entity IDs.
+   */
+  public function validateReferencableEntities(array $ids);
+
+  /**
+   * Validates input from an autocomplete widget that has no ID.
+   *
+   * @param string $input
+   *   Single string from autocomplete widget.
+   * @param array $element
+   *   The form element to set a form error.
+   *
+   * @return int|null
+   *   Value of a matching entity ID, or NULL if none.
+   *
+   * @see \Drupal\entityreference\Plugin\field\widget::elementValidate()
+   */
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form);
+
+  /**
+   * Allows the selection to alter the SelectQuery generated by EntityFieldQuery.
+   *
+   * @param \Drupal\Core\Database\Query\SelectInterface $query
+   *   A Select Query object.
+   */
+  public function entityFieldQueryAlter(SelectInterface $query);
+
+  /**
+   * Generates a settings form for this selection.
+   *
+   * @param array $field
+   *   A field data structure.
+   * @param array $instance
+   *   A field instance data structure.
+   *
+   * @return array
+   *   A Form API array.
+   */
+  public static function settingsForm($field, $instance);
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/comment/Comment.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/comment/Comment.php
new file mode 100644
index 0000000..664e45a
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/comment/Comment.php
@@ -0,0 +1,62 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\Type\Selection\comment\Comment.
+ */
+
+namespace Drupal\entityreference\Plugin\Type\Selection\comment;
+
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entityreference\Plugin\entityreference\Selection\SelectionBase;
+
+/**
+ * Provides specific access control for the comment entity type.
+ */
+class Comment extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::entityFieldQueryAlter().
+   */
+  public function entityFieldQueryAlter(SelectInterface $query) {
+    // Adding the 'comment_access' tag is sadly insufficient for comments: core
+    // requires us to also know about the concept of 'published' and
+    // 'unpublished'.
+    if (!user_access('administer comments')) {
+      $tables = $query->getTables();
+      $query->condition(key($tables) . '.status', COMMENT_PUBLISHED);
+    }
+
+    // The Comment module doesn't implement any proper comment access,
+    // and as a consequence doesn't make sure that comments cannot be viewed
+    // when the user doesn't have access to the node.
+    $tables = $query->getTables();
+    $base_table = key($tables);
+    $node_alias = $query->innerJoin('node', 'n', '%alias.nid = ' . $base_table . '.nid');
+    // Pass the query to the node access control.
+    $this->reAlterQuery($query, 'node_access', $node_alias);
+
+    // Alas, the comment entity exposes a bundle, but doesn't have a bundle
+    // column in the database. We have to alter the query ourselves to go fetch
+    // the bundle.
+    $conditions = &$query->conditions();
+    foreach ($conditions as $key => &$condition) {
+      if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'node_type') {
+        $condition['field'] = $node_alias . '.type';
+        foreach ($condition['value'] as &$value) {
+          if (substr($value, 0, 13) == 'comment_node_') {
+            $value = substr($value, 13);
+          }
+        }
+        break;
+      }
+    }
+
+    // Passing the query to node_query_node_access_alter() is sadly
+    // insufficient for nodes.
+    // @see SelectionEntityTypeNode::entityFieldQueryAlter()
+    if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
+      $query->condition($node_alias . '.status', 1);
+    }
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/file/File.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/file/File.php
new file mode 100644
index 0000000..0965d7c
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/file/File.php
@@ -0,0 +1,32 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\Type\Selection\file\File.
+ */
+
+namespace Drupal\entityreference\Plugin\Type\Selection\file;
+
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entityreference\Plugin\entityreference\Selection\SelectionBase;
+
+/**
+ * Provides specific access control for the file entity type.
+ */
+class File extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::entityFieldQueryAlter().
+   */
+  public function entityFieldQueryAlter(SelectInterface $query) {
+    // Core forces us to know about 'permanent' vs. 'temporary' files.
+    $tables = $query->getTables();
+    $base_table = key($tables);
+    $query->condition('status', FILE_STATUS_PERMANENT);
+
+    // Access control to files is a very difficult business. For now, we are not
+    // going to give it a shot.
+    // @todo: fix this when core access control is less insane.
+    return $query;
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/node/Node.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/node/Node.php
new file mode 100644
index 0000000..b4693d8
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/node/Node.php
@@ -0,0 +1,32 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\Type\Selection\node\Node.
+ */
+
+namespace Drupal\entityreference\Plugin\Type\Selection\node;
+
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entityreference\Plugin\entityreference\Selection\SelectionBase;
+
+/**
+ * Provides specific access control for the node entity type.
+ */
+class Node extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::entityFieldQueryAlter().
+   */
+  public function entityFieldQueryAlter(SelectInterface $query) {
+    // Adding the 'node_access' tag is sadly insufficient for nodes: core
+    // requires us to also know about the concept of 'published' and
+    // 'unpublished'. We need to do that as long as there are no access control
+    // modules in use on the site. As long as one access control module is there,
+    // it is supposed to handle this check.
+    if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
+      $tables = $query->getTables();
+      $query->condition(key($tables) . '.status', NODE_PUBLISHED);
+    }
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/taxonomy/Term.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/taxonomy/Term.php
new file mode 100644
index 0000000..b7b50b4
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/taxonomy/Term.php
@@ -0,0 +1,43 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\Type\Selection\taxonomy\Term.
+ */
+
+namespace Drupal\entityreference\Plugin\Type\Selection\taxonomy;
+
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entityreference\Plugin\entityreference\Selection\SelectionBase;
+
+/**
+ * Provides specific access control for the taxonomy_term entity type.
+ */
+class Term extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::entityFieldQueryAlter().
+   */
+  public function entityFieldQueryAlter(SelectInterface $query) {
+    // The Taxonomy module doesn't implement any proper taxonomy term access,
+    // and as a consequence doesn't make sure that taxonomy terms cannot be
+    // viewed when the user doesn't have access to the vocabulary.
+    $tables = $query->getTables();
+    $base_table = key($tables);
+    $vocabulary_alias = $query->innerJoin('taxonomy_vocabulary', 'n', '%alias.vid = ' . $base_table . '.vid');
+    $query->addMetadata('base_table', $vocabulary_alias);
+    // Pass the query to the taxonomy access control.
+    $this->reAlterQuery($query, 'taxonomy_vocabulary_access', $vocabulary_alias);
+
+    // Also, the taxonomy term entity exposes a bundle, but doesn't have a
+    // bundle column in the database. We have to alter the query ourselves to go
+    // fetch the bundle.
+    $conditions = &$query->conditions();
+    foreach ($conditions as $key => &$condition) {
+      if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'vocabulary_machine_name') {
+        $condition['field'] = $vocabulary_alias . '.machine_name';
+        break;
+      }
+    }
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/user/User.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/user/User.php
new file mode 100644
index 0000000..58ac7a2
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/Selection/user/User.php
@@ -0,0 +1,74 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\Type\Selection\user\User.
+ */
+
+namespace Drupal\entityreference\Plugin\Type\Selection\user;
+
+use Drupal\Core\Database\Database;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entityreference\Plugin\entityreference\Selection\SelectionBase;
+
+/**
+ * Provides specific access control for the user entity type.
+ */
+class User extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::buildEntityFieldQuery().
+   */
+  public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
+    $query = parent::buildEntityFieldQuery($match, $match_operator);
+
+    // The user entity doesn't have a label column.
+    if (isset($match)) {
+      $query->propertyCondition('name', $match, $match_operator);
+    }
+
+    // Adding the 'user_access' tag is sadly insufficient for users: core
+    // requires us to also know about the concept of 'blocked' and 'active'.
+    if (!user_access('administer users')) {
+      $query->propertyCondition('status', 1);
+    }
+    return $query;
+  }
+
+  /**
+   * Overrides SelectionBase::entityFieldQueryAlter().
+   */
+  public function entityFieldQueryAlter(SelectInterface $query) {
+    if (user_access('administer users')) {
+      // In addition, if the user is administrator, we need to make sure to
+      // match the anonymous user, that doesn't actually have a name in the
+      // database.
+      $conditions = &$query->conditions();
+      foreach ($conditions as $key => $condition) {
+        if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
+          // Remove the condition.
+          unset($conditions[$key]);
+
+          // Re-add the condition and a condition on uid = 0 so that we end up
+          // with a query in the form:
+          // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
+          $or = db_or();
+          $or->condition($condition['field'], $condition['value'], $condition['operator']);
+          // Sadly, the Database layer doesn't allow us to build a condition
+          // in the form ':placeholder = :placeholder2', because the 'field'
+          // part of a condition is always escaped.
+          // As a (cheap) workaround, we separately build a condition with no
+          // field, and concatenate the field and the condition separately.
+          $value_part = db_and();
+          $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
+          $value_part->compile(Database::getConnection(), $query);
+          $or->condition(db_and()
+            ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name(user_load(0))))
+            ->condition('users.uid', 0)
+          );
+          $query->condition($or);
+        }
+      }
+    }
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/SelectionPluginManager.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/SelectionPluginManager.php
new file mode 100644
index 0000000..71db00e
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/Type/SelectionPluginManager.php
@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\Type\SelectionPluginManager.
+ */
+
+namespace Drupal\entityreference\Plugin\Type;
+
+use Drupal\Component\Plugin\PluginManagerBase;
+use Drupal\Core\Plugin\Discovery\CacheDecorator;
+use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
+
+/**
+ * Plugin type manager for the Entity Reference Selection plugin.
+ */
+class SelectionPluginManager extends PluginManagerBase {
+
+  /**
+   * Constructs a WidgetPluginManager object.
+   */
+  public function __construct() {
+    $this->baseDiscovery = new AnnotatedClassDiscovery('entityreference', 'Selection');
+    $this->discovery = new CacheDecorator($this->baseDiscovery, 'entityreference_selection');
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/entityreference/selection/SelectionBase.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/entityreference/selection/SelectionBase.php
new file mode 100644
index 0000000..cb5f7fb
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/entityreference/selection/SelectionBase.php
@@ -0,0 +1,300 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\entityreference\Selection\SelectionBase.
+ */
+
+namespace Drupal\entityreference\Plugin\entityreference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Query\AlterableInterface;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\Core\Entity\EntityFieldQuery;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\entityreference\Plugin\Type\Selection\SelectionBroken;
+use Drupal\entityreference\Plugin\Type\Selection\SelectionInterface;
+use Drupal\field\Plugin\PluginSettingsBase;
+
+/**
+ * Plugin implementation of the 'selection' entityreference.
+ *
+ * @Plugin(
+ *   id = "base",
+ *   module = "entityreference",
+ *   label = @Translation("Simple selection")
+ * )
+ */
+class SelectionBase extends PluginSettingsBase implements SelectionInterface {
+
+  public function __construct($field, $instance = NULL, EntityInterface $entity = NULL) {
+    $this->field = $field;
+    $this->instance = $instance;
+    $this->entity = $entity;
+  }
+
+  /**
+   * Implements SelectionInterface::settingsForm().
+   */
+  public static function settingsForm($field, $instance) {
+    $entity_info = entity_get_info($field['settings']['target_type']);
+
+    // Merge-in default values.
+    $field['settings']['handler_settings'] += array(
+      'target_bundles' => array(),
+      'sort' => array(
+        'type' => 'none',
+      )
+    );
+
+    if (!empty($entity_info['entity keys']['bundle'])) {
+      $bundles = array();
+      foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
+        $bundles[$bundle_name] = $bundle_info['label'];
+      }
+
+      $form['target_bundles'] = array(
+        '#type' => 'checkboxes',
+        '#title' => t('Target bundles'),
+        '#options' => $bundles,
+        '#default_value' => $field['settings']['handler_settings']['target_bundles'],
+        '#size' => 6,
+        '#multiple' => TRUE,
+        '#description' => t('The bundles of the entity type that can be referenced. Optional, leave empty for all bundles.'),
+        '#element_validate' => array('_entityreference_element_validate_filter'),
+      );
+    }
+    else {
+      $form['target_bundles'] = array(
+        '#type' => 'value',
+        '#value' => array(),
+      );
+    }
+
+    $form['sort']['type'] = array(
+      '#type' => 'select',
+      '#title' => t('Sort by'),
+      '#options' => array(
+        'none' => t("Don't sort"),
+        'property' => t('A property of the base table of the entity'),
+        'field' => t('A field attached to this entity'),
+      ),
+      '#ajax' => TRUE,
+      '#limit_validation_errors' => array(),
+      '#default_value' => $field['settings']['handler_settings']['sort']['type'],
+    );
+
+    $form['sort']['settings'] = array(
+      '#type' => 'container',
+      '#attributes' => array('class' => array('entityreference-settings')),
+      '#process' => array('_entityreference_form_process_merge_parent'),
+    );
+
+    if ($field['settings']['handler_settings']['sort']['type'] == 'property') {
+      // Merge-in default values.
+      $field['settings']['handler_settings']['sort'] += array(
+        'property' => NULL,
+      );
+
+      $form['sort']['settings']['property'] = array(
+        '#type' => 'select',
+        '#title' => t('Sort property'),
+        '#required' => TRUE,
+        '#options' => drupal_map_assoc($entity_info['schema_fields_sql']['base table']),
+        '#default_value' => $field['settings']['handler_settings']['sort']['property'],
+      );
+    }
+    elseif ($field['settings']['handler_settings']['sort']['type'] == 'field') {
+      // Merge-in default values.
+      $field['settings']['handler_settings']['sort'] += array(
+        'field' => NULL,
+      );
+
+      $fields = array();
+      foreach (field_info_instances($field['settings']['target_type']) as $bundle_name => $bundle_instances) {
+        foreach ($bundle_instances as $instance_name => $instance_info) {
+          $field_info = field_info_field($instance_name);
+          foreach ($field_info['columns'] as $column_name => $column_info) {
+            $fields[$instance_name . ':' . $column_name] = t('@label (column @column)', array('@label' => $instance_info['label'], '@column' => $column_name));
+          }
+        }
+      }
+
+      $form['sort']['settings']['field'] = array(
+        '#type' => 'select',
+        '#title' => t('Sort field'),
+        '#required' => TRUE,
+        '#options' => $fields,
+        '#default_value' => $field['settings']['handler_settings']['sort']['field'],
+      );
+    }
+
+    if ($field['settings']['handler_settings']['sort']['type'] != 'none') {
+      // Merge-in default values.
+      $field['settings']['handler_settings']['sort'] += array(
+        'direction' => 'ASC',
+      );
+
+      $form['sort']['settings']['direction'] = array(
+        '#type' => 'select',
+        '#title' => t('Sort direction'),
+        '#required' => TRUE,
+        '#options' => array(
+          'ASC' => t('Ascending'),
+          'DESC' => t('Descending'),
+        ),
+        '#default_value' => $field['settings']['handler_settings']['sort']['direction'],
+      );
+    }
+
+    return $form;
+  }
+
+  /**
+   * Implements SelectionInterface::getReferencableEntities().
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+    $entity_type = $this->field['settings']['target_type'];
+
+    $query = $this->buildEntityFieldQuery($match, $match_operator);
+    if ($limit > 0) {
+      $query->range(0, $limit);
+    }
+
+    $result = $query->execute();
+
+    if (empty($result[$entity_type])) {
+      return array();
+    }
+
+    $options = array();
+    $entities = entity_load_multiple($entity_type, array_keys($result[$entity_type]));
+    foreach ($entities as $entity_id => $entity) {
+      $options[$entity_id] = check_plain($entity->label());
+    }
+
+    return $options;
+  }
+
+  /**
+   * Implements SelectionInterface::countReferencableEntities().
+   */
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
+    $query = $this->buildEntityFieldQuery($match, $match_operator);
+    return $query
+      ->count()
+      ->execute();
+  }
+
+  /**
+   * Implements SelectionInterface::validateReferencableEntities().
+   */
+  public function validateReferencableEntities(array $ids) {
+    if ($ids) {
+      $entity_type = $this->field['settings']['target_type'];
+      $query = $this->buildEntityFieldQuery();
+      $query->entityCondition('entity_id', $ids, 'IN');
+      $result = $query->execute();
+      if (!empty($result[$entity_type])) {
+        return array_keys($result[$entity_type]);
+      }
+    }
+
+    return array();
+  }
+
+  /**
+   * Implements SelectionInterface::validateAutocompleteInput().
+   */
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
+      $entities = $this->getReferencableEntities($input, '=', 6);
+      if (empty($entities)) {
+        // Error if there are no entities available for a required field.
+        form_error($element, t('There are no entities matching "%value"', array('%value' => $input)));
+      }
+      elseif (count($entities) > 5) {
+        // Error if there are more than 5 matching entities.
+        form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
+          '%value' => $input,
+          '@value' => $input,
+          '@id' => key($entities),
+        )));
+      }
+      elseif (count($entities) > 1) {
+        // More helpful error if there are only a few matching entities.
+        $multiples = array();
+        foreach ($entities as $id => $name) {
+          $multiples[] = $name . ' (' . $id . ')';
+        }
+        form_error($element, t('Multiple entities match this reference; "%multiple"', array('%multiple' => implode('", "', $multiples))));
+      }
+      else {
+        // Take the one and only matching entity.
+        return key($entities);
+      }
+  }
+
+  /**
+   * Builds an EntityFieldQuery to get referencable entities.
+   */
+  protected function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
+    $query = new EntityFieldQuery();
+    $query->entityCondition('entity_type', $this->field['settings']['target_type']);
+    if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
+      $query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
+    }
+    if (isset($match)) {
+      $entity_info = entity_get_info($this->field['settings']['target_type']);
+      if (isset($entity_info['entity keys']['label'])) {
+        $query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
+      }
+    }
+
+    // Add a generic entity access tag to the query.
+    $query->addTag($this->field['settings']['target_type'] . '_access');
+    $query->addTag('entityreference');
+    $query->addMetaData('field', $this->field);
+    $query->addMetaData('entityreference_selection_handler', $this);
+
+    // Add the sort option.
+    if (!empty($this->field['settings']['handler_settings']['sort'])) {
+      $sort_settings = $this->field['settings']['handler_settings']['sort'];
+      if ($sort_settings['type'] == 'property') {
+        $query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
+      }
+      elseif ($sort_settings['type'] == 'field') {
+        list($field, $column) = explode(':', $sort_settings['field'], 2);
+        $query->fieldOrderBy($field, $column, $sort_settings['direction']);
+      }
+    }
+
+    return $query;
+  }
+
+  /**
+   * Implements SelectionInterface::entityFieldQueryAlter().
+   */
+  public function entityFieldQueryAlter(SelectInterface $query) { }
+
+  /**
+   * Helper method: Passes a query to the alteration system again.
+   *
+   * This allows Entity Reference to add a tag to an existing query so it can
+   * ask access control mechanisms to alter it again.
+   */
+  protected function reAlterQuery(AlterableInterface $query, $tag, $base_table) {
+    // Save the old tags and metadata.
+    // For some reason, those are public.
+    $old_tags = $query->alterTags;
+    $old_metadata = $query->alterMetaData;
+
+    $query->alterTags = array($tag => TRUE);
+    $query->alterMetaData['base_table'] = $base_table;
+    drupal_alter(array('query', 'query_' . $tag), $query);
+
+    // Restore the tags and metadata.
+    $query->alterTags = $old_tags;
+    $query->alterMetaData = $old_metadata;
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceEntityFormatter.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
new file mode 100644
index 0000000..0863172
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
@@ -0,0 +1,117 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\field\formatter\EntityReferenceEntityFormatter.
+ */
+
+namespace Drupal\entityreference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+
+use Drupal\entityreference\EntityReferenceRecursiveRenderingException;
+use Drupal\entityreference\Plugin\field\formatter\EntityReferenceFormatterBase;
+
+/**
+ * Plugin implementation of the 'entity-reference rendered entity' formatter.
+ *
+ * @Plugin(
+ *   id = "entityreference_entity_view",
+ *   module = "entityreference",
+ *   label = @Translation("Rendered entity"),
+ *   description = @Translation("Display the referenced entities rendered by entity_view()."),
+ *   field_types = {
+ *     "entityreference"
+ *   },
+ *   settings = {
+ *     "view_mode" = "",
+ *     "link" = "FALSE"
+ *   }
+ * )
+ */
+class EntityReferenceEntityFormatter extends EntityReferenceFormatterBase {
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm().
+   */
+  public function settingsForm(array $form, array &$form_state) {
+    $entity_info = entity_get_info($this->field['settings']['target_type']);
+    $options = array();
+    if (!empty($entity_info['view modes'])) {
+      foreach ($entity_info['view modes'] as $view_mode => $view_mode_settings) {
+        $options[$view_mode] = $view_mode_settings['label'];
+      }
+    }
+
+    $elements['view_mode'] = array(
+      '#type' => 'select',
+      '#options' => $options,
+      '#title' => t('View mode'),
+      '#default_value' => $this->getSetting('view_mode'),
+      '#required' => TRUE,
+    );
+
+    $elements['links'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Show links'),
+      '#default_value' => $this->getSetting('links'),
+    );
+
+    return $elements;
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm().
+   */
+  public function settingsSummary() {
+    $summary = array();
+
+    $entity_info = entity_get_info($this->field['settings']['target_type']);
+    $view_mode = $this->getSetting('view_mode');
+    $summary[] = t('Rendered as @mode', array('@mode' => isset($entity_info['view modes'][$view_mode]['label']) ? $entity_info['view modes'][$view_mode]['label'] : $view_mode));
+    $summary[] = $this->getSetting('links') ? t('Display links') : t('Do not display links');
+
+    return implode('<br />', $summary);
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    // Remove un-accessible items.
+    parent::viewElements($entity, $langcode, $items);
+
+    $instance = $this->instance;
+    $field = $this->field;
+    $view_mode = $this->getSetting('view_mode');
+    $links = $this->getSetting('links');
+
+    $target_type = $field['settings']['target_type'];
+
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+      // Protect ourselves from recursive rendering.
+      static $depth = 0;
+      $depth++;
+      if ($depth > 20) {
+        throw new EntityReferenceRecursiveRenderingException(format_string('Recursive rendering detected when rendering entity @entity_type(@entity_id). Aborting rendering.', array('@entity_type' => $entity_type, '@entity_id' => $item['target_id'])));
+      }
+
+      $entity = clone $item['entity'];
+      unset($entity->content);
+      $elements[$delta] = entity_view($entity, $view_mode, $langcode);
+
+      if (empty($links) && isset($result[$delta][$target_type][$item['target_id']]['links'])) {
+        // Hide the element links.
+        $elements[$delta][$target_type][$item['target_id']]['links']['#access'] = FALSE;
+      }
+      $depth = 0;
+    }
+
+
+    return $elements;
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceFormatterBase.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceFormatterBase.php
new file mode 100644
index 0000000..6ecc0b4
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceFormatterBase.php
@@ -0,0 +1,90 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\field\formatter\EntityReferenceFormatterBase.
+ */
+
+namespace Drupal\entityreference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+
+use Drupal\field\Plugin\Type\Formatter\FormatterBase;
+
+/**
+ * Parent plugin for entity-reference formatters.
+ */
+abstract class EntityReferenceFormatterBase extends FormatterBase {
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::prepareView().
+   *
+   * Mark the accessible IDs a user can see. We do not unset unaccessible
+   * values, as other may want to act on those values, even if they can
+   * not be accessed.
+   */
+  public function prepareView(array $entities, $langcode, array &$items) {
+    $target_ids = array();
+
+    // Collect every possible entity attached to any of the entities.
+    foreach ($entities as $id => $entity) {
+      foreach ($items[$id] as $delta => $item) {
+        if (isset($item['target_id'])) {
+          $target_ids[] = $item['target_id'];
+        }
+      }
+    }
+
+    $target_type = $this->field['settings']['target_type'];
+
+    if ($target_ids) {
+      $target_entities = entity_load_multiple($target_type, $target_ids);
+    }
+    else {
+      $target_entities = array();
+    }
+
+    // Iterate through the fieldable entities again to attach the loaded
+    // data.
+    foreach ($entities as $id => $entity) {
+
+      foreach ($items[$id] as $delta => $item) {
+        $items[$id][$delta]['entity'] = $target_entities[$item['target_id']];
+
+        if (!isset($target_entities[$item['target_id']])) {
+          continue;
+        }
+
+        $entity = $target_entities[$item['target_id']];
+
+        // TODO: Improve when we have entity_access().
+        $entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE;
+        if (!$entity_access) {
+          continue;
+        }
+
+        // Mark item as accessible.
+        $items[$id][$delta]['access'] = TRUE;
+      }
+    }
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::viewElements().
+   *
+   * Remove unaccessible values.
+   *
+   * @see Drupal\entityreference\Plugin\field\formatter\EntityReferenceFormatterBase::prepareView().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    // Remove unaccessible items.
+    foreach ($items as $delta => $item) {
+      if (empty($item['access'])) {
+        unset($items[$delta]);
+      }
+    }
+    return array();
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceIdFormatter.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceIdFormatter.php
new file mode 100644
index 0000000..89f9f98
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceIdFormatter.php
@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\field\formatter\EntityReferenceIdFormatter.
+ */
+
+namespace Drupal\entityreference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+
+use Drupal\entityreference\Plugin\field\formatter\EntityReferenceFormatterBase;
+
+/**
+ * Plugin implementation of the 'entity-reference ID' formatter.
+ *
+ * @Plugin(
+ *   id = "entityreference_entity_id",
+ *   module = "entityreference",
+ *   label = @Translation("Entity ID"),
+ *   description = @Translation("Display the ID of the referenced entities."),
+ *   field_types = {
+ *     "entityreference"
+ *   }
+ * )
+ */
+class EntityReferenceIdFormatter extends EntityReferenceFormatterBase {
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+      $elements[$delta] = array('#markup' => check_plain($item['target_id']));
+    }
+
+    return $elements;
+  }
+
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceLabelFormatter.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
new file mode 100644
index 0000000..43d7132
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
@@ -0,0 +1,85 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\field\formatter\EntityReferenceLabelFormatter.
+ */
+
+namespace Drupal\entityreference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+
+use Drupal\entityreference\Plugin\field\formatter\EntityReferenceFormatterBase;
+
+/**
+ * Plugin implementation of the 'entity-reference label' formatter.
+ *
+ * @Plugin(
+ *   id = "entityreference_label",
+ *   module = "entityreference",
+ *   label = @Translation("Label"),
+ *   description = @Translation("Display the label of the referenced entities."),
+ *   field_types = {
+ *     "entityreference"
+ *   },
+ *   settings = {
+ *     "link" = "FALSE"
+ *   }
+ * )
+ */
+class EntityReferenceLabelFormatter extends EntityReferenceFormatterBase {
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm().
+   */
+  public function settingsForm(array $form, array &$form_state) {
+    $elements['link'] = array(
+      '#title' => t('Link label to the referenced entity'),
+      '#type' => 'checkbox',
+      '#default_value' => $this->getSetting('link'),
+    );
+
+    return $elements;
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm().
+   */
+  public function settingsSummary() {
+    $summary = array();
+    $summary[] = $this->getSetting('link') ? t('Link to the referenced entity') : t('No link');
+
+    return implode('<br />', $summary);
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    // Remove un-accessible items.
+    parent::viewElements($entity, $langcode, $items);
+
+    $instance = $this->instance;
+    $field = $this->field;
+
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+      $entity = $item['entity'];
+      $label = $entity->label();
+      // If the link is to be displayed and the entity has a uri,
+      // display a link.
+      if ($this->getSetting('link') && $uri = $entity->uri()) {
+        $elements[$delta] = array('#markup' => l($label, $uri['path'], $uri['options']));
+      }
+      else {
+        $elements[$delta] = array('#markup' => check_plain($label));
+      }
+    }
+
+    return $elements;
+  }
+
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteTagsWidget.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteTagsWidget.php
new file mode 100644
index 0000000..bb38650
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteTagsWidget.php
@@ -0,0 +1,78 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\field\widget\AutocompleteTagsWidget.
+ */
+
+namespace Drupal\entityreference\Plugin\field\widget;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\field\Plugin\Type\Widget\WidgetBase;
+
+use Drupal\entityreference\Plugin\field\widget\AutocompleteWidgetBase;
+
+/**
+ * Plugin implementation of the 'entityreference autocomplete-tags' widget.
+ *
+ * @todo: Check if the following statement is still correct
+ * The autocomplete path doesn't have a default here, because it's not the
+ * the two widgets, and the Field API doesn't update default settings when
+ * the widget changes.
+ *
+ * @Plugin(
+ *   id = "entityreference_autocomplete_tags",
+ *   module = "entityreference",
+ *   label = @Translation("Autocomplete (Tags style)"),
+ *   description = @Translation("An autocomplete text field."),
+ *   field_types = {
+ *     "entityreference"
+ *   },
+ *   settings = {
+ *     "match_operator" = "CONTAINS",
+ *     "size" = 60,
+ *     "path" = ""
+ *   },
+ *   multiple_values = FIELD_BEHAVIOR_CUSTOM
+ * )
+ */
+class AutocompleteTagsWidget extends AutocompleteWidgetBase {
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::formElement().
+   */
+  public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
+    return $this->prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entityreference/autocomplete/tags');
+  }
+
+  /**
+   * Implements Drupal\entityreference\Plugin\field\widget\DefaultAutocompleteWidget::elementValidate()
+   */
+  public function elementValidate($element, &$form_state) {
+    $value = array();
+    // If a value was entered into the autocomplete.
+    if (!empty($element['#value'])) {
+      $entities = drupal_explode_tags($element['#value']);
+      $value = array();
+      foreach ($entities as $entity) {
+        // Take "label (entity id)', match the id from parenthesis.
+        if (preg_match("/.+\((\d+)\)/", $entity, $matches)) {
+          $value[] = array(
+            'target_id' => $matches[1],
+          );
+        }
+        else {
+          // Try to get a match from the input string when the user didn't use the
+          // autocomplete but filled in a value manually.
+        $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
+        $handler = entityreference_get_selection_handler($field, $instance);
+          $value[] = array(
+            'target_id' => $handler->validateAutocompleteInput($entity, $element, $form_state, $form),
+          );
+        }
+      }
+    }
+    form_set_value($element, $value, $form_state);
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteWidget.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteWidget.php
new file mode 100644
index 0000000..ce4e62f
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteWidget.php
@@ -0,0 +1,80 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\field\widget\AutocompleteWidget.
+ */
+
+namespace Drupal\entityreference\Plugin\field\widget;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\field\Plugin\Type\Widget\WidgetBase;
+
+use Drupal\entityreference\Plugin\field\widget\AutocompleteWidgetBase;
+
+/**
+ * Plugin implementation of the 'entityreference autocomplete' widget.
+ *
+ * @todo: Check if the following statement is still correct
+ * The autocomplete path doesn't have a default here, because it's not the
+ * the two widgets, and the Field API doesn't update default settings when
+ * the widget changes.
+ *
+ * @Plugin(
+ *   id = "entityreference_autocomplete",
+ *   module = "entityreference",
+ *   label = @Translation("Autocomplete"),
+ *   description = @Translation("An autocomplete text field."),
+ *   field_types = {
+ *     "entityreference"
+ *   },
+ *   settings = {
+ *     "match_operator" = "CONTAINS",
+ *     "size" = 60,
+ *     "path" = ""
+ *   }
+ * )
+ */
+class AutocompleteWidget extends AutocompleteWidgetBase {
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::formElement().
+   */
+  public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
+    // We let the Field API handles multiple values for us, only take
+    // care of the one matching our delta.
+    if (isset($items[$delta])) {
+      $items = array($items[$delta]);
+    }
+    else {
+      $items = array();
+    }
+
+    $element = $this->prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entityreference/autocomplete/single');
+    return array('target_id' => $element);
+  }
+
+  /**
+   * Implements Drupal\entityreference\Plugin\field\widget\DefaultAutocompleteWidget::elementValidate()
+   */
+  public function elementValidate($element, &$form_state) {
+    // If a value was entered into the autocomplete.
+    $value = '';
+    if (!empty($element['#value'])) {
+      // Take "label (entity id)', match the id from parenthesis.
+      if (preg_match("/.+\((\d+)\)/", $element['#value'], $matches)) {
+        $value = $matches[1];
+      }
+      else {
+        // Try to get a match from the input string when the user didn't use the
+        // autocomplete but filled in a value manually.
+        $field = field_info_field($element['#field_name']);
+        $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
+        $handler = entityreference_get_selection_handler($field, $instance);
+        $value = $handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form);
+      }
+    }
+    form_set_value($element, $value, $form_state);
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteWidgetBase.php b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteWidgetBase.php
new file mode 100644
index 0000000..810b1ab
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Plugin/field/widget/AutocompleteWidgetBase.php
@@ -0,0 +1,137 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\entityreference\Plugin\field\widget\AutocompleteWidgetBase.
+ */
+
+namespace Drupal\entityreference\Plugin\field\widget;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\field\Plugin\Type\Widget\WidgetBase;
+
+/**
+ * Parent plugin for entity-reference autocomplete widgets.
+ */
+abstract class AutocompleteWidgetBase extends WidgetBase {
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::settingsForm().
+   */
+  public function settingsForm(array $form, array &$form_state) {
+
+    $form['match_operator'] = array(
+      '#type' => 'select',
+      '#title' => t('Autocomplete matching'),
+      '#default_value' => $this->getSetting('match_operator'),
+      '#options' => array(
+        'STARTS_WITH' => t('Starts with'),
+        'CONTAINS' => t('Contains'),
+      ),
+      '#description' => t('Select the method used to collect autocomplete suggestions. Note that <em>Contains</em> can cause performance issues on sites with thousands of nodes.'),
+    );
+    $form['size'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Size of textfield'),
+      '#default_value' => $this->getSetting('size'),
+      '#element_validate' => array('form_validate_number'),
+      // Minimum value for form_validate_number().
+      '#min' => 1,
+      '#required' => TRUE,
+    );
+
+    return $form;
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::formElement().
+   */
+  public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
+    $element = $this->prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entityreference/autocomplete/single');
+    return array('target_id' => $element);
+  }
+
+  /**
+   * Prepapre the element.
+   *
+   * @default_path
+   *   The menu item to be used in the autocomplete path.
+   */
+  protected function prepareElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state, $default_path) {
+    $instance = $this->instance;
+    $field = $this->field;
+    $entity = isset($element['#entity']) ? $element['#entity'] : NULL;
+
+    // Prepare the autocomplete path.
+    $path = $this->getSetting('path');
+    $autocomplete_path = !empty($path) ? $path : $default_path;
+    $autocomplete_path .= '/' . $field['field_name'] . '/' . $instance['entity_type'] . '/' . $instance['bundle'] . '/';
+
+    // Use <NULL> as a placeholder in the URL when we don't have an entity.
+    // Most webservers collapse two consecutive slashes.
+    $id = 'NULL';
+    if ($entity) {
+      if ($eid = $entity->id()) {
+        $id = $eid;
+      }
+    }
+    $autocomplete_path .= $id;
+
+    $element += array(
+      '#type' => 'textfield',
+      '#maxlength' => 1024,
+      '#default_value' => implode(', ', $this->getLabels($items)),
+      '#autocomplete_path' => $autocomplete_path,
+      '#size' => $this->getSetting('size'),
+      '#element_validate' => array(array($this, 'elementValidate')),
+    );
+    return $element;
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::errorElement().
+   */
+  public function errorElement(array $element, array $error, array $form, array &$form_state) {
+    return $element['target_id'];
+  }
+
+  /**
+   * Element validate.
+   */
+  public function elementValidate($element, &$form_state) {
+  }
+
+  /**
+   * Get the entity labels.
+   */
+  protected function getLabels(array $items) {
+    $instance = $this->instance;
+    $field = $this->field;
+
+    $entity = isset($element['#entity']) ? $element['#entity'] : NULL;
+    $handler = entityreference_get_selection_handler($field, $instance, $entity);
+
+    $entity_ids = array();
+    $entity_labels = array();
+
+    // Build an array of entities ID.
+    foreach ($items as $item) {
+      $entity_ids[] = $item['target_id'];
+    }
+
+    // Load those entities and loop through them to extract their labels.
+    $entities = entity_load_multiple($field['settings']['target_type'], $entity_ids);
+
+    foreach ($entities as $entity_id => $entity_item) {
+      $label = $entity_item->label();
+      $key = "$label ($entity_id)";
+      // Labels containing commas or quotes must be wrapped in quotes.
+      if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
+        $key = '"' . str_replace('"', '""', $key) . '"';
+      }
+      $entity_labels[] = $key;
+    }
+    return $entity_labels;
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Tests/EntityReferenceAdminTest.php b/core/modules/entityreference/lib/Drupal/entityreference/Tests/EntityReferenceAdminTest.php
new file mode 100644
index 0000000..45e17d5
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Tests/EntityReferenceAdminTest.php
@@ -0,0 +1,118 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\entityreference\Tests\EntityReferenceAdminTest.
+ */
+
+namespace Drupal\entityreference\Tests;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests the Entity reference Admin UI.
+ */
+class EntityReferenceAdminTest extends WebTestBase {
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity Reference UI',
+      'description' => 'Tests for the administrative UI.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  public static $modules = array('field_ui', 'entityreference');
+
+  public function setUp() {
+    parent::setUp();
+
+    // Create test user.
+    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer content types'));
+    $this->drupalLogin($this->admin_user);
+
+    // Create content type, with underscores.
+    $type_name = strtolower($this->randomName(8)) . '_test';
+    $type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name));
+    $this->type = $type->type;
+  }
+
+  protected function assertFieldSelectOptions($name, $expected_options) {
+    $xpath = $this->buildXPathQuery('//select[@name=:name]', array(':name' => $name));
+    $fields = $this->xpath($xpath);
+    if ($fields) {
+      $field = $fields[0];
+      $options = $this->getAllOptionsList($field);
+      return $this->assertIdentical($options, $expected_options);
+    }
+    else {
+      return $this->fail(t('Unable to find field @name', array('@name' => $name)));
+    }
+  }
+
+  /**
+   * Extract all the options of a select element.
+   */
+  protected function getAllOptionsList($element) {
+    $options = array();
+    // Add all options items.
+    foreach ($element->option as $option) {
+      $options[] = (string) $option['value'];
+    }
+    // TODO: support optgroup.
+    return $options;
+  }
+
+  public function testFieldAdminHandler() {
+    $bundle_path = 'admin/structure/types/manage/' . $this->type;
+
+    // First step: 'Add new field' on the 'Manage fields' page.
+    $this->drupalPost($bundle_path . '/fields', array(
+      'fields[_add_new_field][label]' => 'Test label',
+      'fields[_add_new_field][field_name]' => 'test',
+      'fields[_add_new_field][type]' => 'entityreference',
+      'fields[_add_new_field][widget_type]' => 'entityreference_autocomplete',
+    ), t('Save'));
+
+    // Node should be selected by default.
+    $this->assertFieldByName('field[settings][target_type]', 'node');
+    // The base handler should be selected by default.
+    $this->assertFieldByName('field[settings][handler]', 'base');
+
+    // The base handler settings should be diplayed.
+    $entity_type = 'node';
+    $entity_info = entity_get_info($entity_type);
+    foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
+      $this->assertFieldByName('field[settings][handler_settings][target_bundles][' . $bundle_name . ']');
+    }
+
+    // Test the sort settings.
+    $options = array('none', 'property', 'field');
+    $this->assertFieldSelectOptions('field[settings][handler_settings][sort][type]', $options);
+    // Option 0: no sort.
+    $this->assertFieldByName('field[settings][handler_settings][sort][type]', 'none');
+    $this->assertNoFieldByName('field[settings][handler_settings][sort][property]');
+    $this->assertNoFieldByName('field[settings][handler_settings][sort][field]');
+    $this->assertNoFieldByName('field[settings][handler_settings][sort][direction]');
+    // Option 1: sort by property.
+    $this->drupalPostAJAX(NULL, array('field[settings][handler_settings][sort][type]' => 'property'), 'field[settings][handler_settings][sort][type]');
+    $this->assertFieldByName('field[settings][handler_settings][sort][property]', '');
+    $this->assertNoFieldByName('field[settings][handler_settings][sort][field]');
+    $this->assertFieldByName('field[settings][handler_settings][sort][direction]', 'ASC');
+    // Option 2: sort by field.
+    $this->drupalPostAJAX(NULL, array('field[settings][handler_settings][sort][type]' => 'field'), 'field[settings][handler_settings][sort][type]');
+    $this->assertNoFieldByName('field[settings][handler_settings][sort][property]');
+    $this->assertFieldByName('field[settings][handler_settings][sort][field]', '');
+    $this->assertFieldByName('field[settings][handler_settings][sort][direction]', 'ASC');
+    // Set back to no sort.
+    $this->drupalPostAJAX(NULL, array('field[settings][handler_settings][sort][type]' => 'none'), 'field[settings][handler_settings][sort][type]');
+
+    // Second step: 'Instance settings' form.
+    $this->drupalPost(NULL, array(), t('Save field settings'));
+
+    // Third step: confirm.
+    $this->drupalPost(NULL, array(), t('Save settings'));
+
+    // Check that the field appears in the overview form.
+    $this->assertFieldByXPath('//table[@id="field-overview"]//td[1]', 'Test label', t('Field was created and appears in the overview page.'));
+  }
+}
diff --git a/core/modules/entityreference/lib/Drupal/entityreference/Tests/EntityReferenceSelectionAccessTest.php b/core/modules/entityreference/lib/Drupal/entityreference/Tests/EntityReferenceSelectionAccessTest.php
new file mode 100644
index 0000000..fa7a508
--- /dev/null
+++ b/core/modules/entityreference/lib/Drupal/entityreference/Tests/EntityReferenceSelectionAccessTest.php
@@ -0,0 +1,440 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\entityreference\Tests\EntityReferenceSelectionAccessTest.
+ */
+
+namespace Drupal\entityreference\Tests;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests the Entity reference Selection plugin.
+ */
+class EntityReferenceSelectionAccessTest extends WebTestBase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity Reference Handlers',
+      'description' => 'Tests for the base handlers provided by Entity Reference.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  public static $modules = array('node', 'comment', 'entityreference');
+
+  protected function assertReferencable($field, $tests, $handler_name) {
+    $handler = entityreference_get_selection_handler($field);
+
+    foreach ($tests as $test) {
+      foreach ($test['arguments'] as $arguments) {
+        $result = call_user_func_array(array($handler, 'getReferencableEntities'), $arguments);
+        $this->assertEqual($result, $test['result'], t('Valid result set returned by @handler.', array('@handler' => $handler_name)));
+
+        $result = call_user_func_array(array($handler, 'countReferencableEntities'), $arguments);
+        $this->assertEqual($result, count($test['result']), t('Valid count returned by @handler.', array('@handler' => $handler_name)));
+      }
+    }
+  }
+
+  /**
+   * Test the node-specific overrides of the entity handler.
+   */
+  public function testNodeHandler() {
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'handler' => 'base',
+        'target_type' => 'node',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+        ),
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entityreference',
+      'cardinality' => '1',
+    );
+
+    // Build a set of test data.
+    // Titles contain HTML-special characters to test escaping.
+    $node_values = array(
+      'published1' => array(
+        'type' => 'article',
+        'status' => NODE_PUBLISHED,
+        'title' => 'Node published1 (<&>)',
+        'uid' => 1,
+      ),
+      'published2' => array(
+        'type' => 'article',
+        'status' => NODE_PUBLISHED,
+        'title' => 'Node published2 (<&>)',
+        'uid' => 1,
+      ),
+      'unpublished' => array(
+        'type' => 'article',
+        'status' => NODE_NOT_PUBLISHED,
+        'title' => 'Node unpublished (<&>)',
+        'uid' => 1,
+      ),
+    );
+
+    $nodes = array();
+    $node_labels = array();
+    foreach ($node_values as $key => $values) {
+      $node = entity_create('node', $values);
+      $node->save();
+      $nodes[$key] = $node;
+      $node_labels[$key] = check_plain($node->label());
+    }
+
+    // Test as a non-admin.
+    $normal_user = $this->drupalCreateUser(array('access content'));
+    $GLOBALS['user'] = $normal_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          $nodes['published1']->nid => $node_labels['published1'],
+          $nodes['published2']->nid => $node_labels['published2'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('published1', 'CONTAINS'),
+          array('Published1', 'CONTAINS'),
+        ),
+        'result' => array(
+          $nodes['published1']->nid => $node_labels['published1'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('published2', 'CONTAINS'),
+          array('Published2', 'CONTAINS'),
+        ),
+        'result' => array(
+          $nodes['published2']->nid => $node_labels['published2'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('invalid node', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+      array(
+        'arguments' => array(
+          array('Node unpublished', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+    );
+    $this->assertReferencable($field, $referencable_tests, 'Node handler');
+
+    // Test as an admin.
+    $admin_user = $this->drupalCreateUser(array('access content', 'bypass node access'));
+    $GLOBALS['user'] = $admin_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          $nodes['published1']->nid => $node_labels['published1'],
+          $nodes['published2']->nid => $node_labels['published2'],
+          $nodes['unpublished']->nid => $node_labels['unpublished'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('Node unpublished', 'CONTAINS'),
+        ),
+        'result' => array(
+          $nodes['unpublished']->nid => $node_labels['unpublished'],
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $referencable_tests, 'Node handler (admin)');
+  }
+
+  /**
+   * Test the user-specific overrides of the entity handler.
+   */
+  public function testUserHandler() {
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'handler' => 'base',
+        'target_type' => 'user',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+        ),
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entityreference',
+      'cardinality' => '1',
+    );
+
+    // Build a set of test data.
+    $user_values = array(
+      'anonymous' => user_load(0),
+      'admin' => user_load(1),
+      'non_admin' => array(
+        'name' => 'non_admin <&>',
+        'mail' => 'non_admin@example.com',
+        'roles' => array(),
+        'pass' => user_password(),
+        'status' => 1,
+      ),
+      'blocked' => array(
+        'name' => 'blocked <&>',
+        'mail' => 'blocked@example.com',
+        'roles' => array(),
+        'pass' => user_password(),
+        'status' => 0,
+      ),
+    );
+
+    $user_values['anonymous']->name = config('user.settings')->get('anonymous');
+    $users = array();
+
+    $user_labels = array();
+    foreach ($user_values as $key => $values) {
+      if (is_array($values)) {
+        $account = entity_create('user', $values);
+        $account->save();
+      }
+      else {
+        $account = $values;
+      }
+      $users[$key] = $account;
+      $user_labels[$key] = check_plain($account->name);
+    }
+
+    // Test as a non-admin.
+    $GLOBALS['user'] = $users['non_admin'];
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          $users['admin']->uid => $user_labels['admin'],
+          $users['non_admin']->uid => $user_labels['non_admin'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('non_admin', 'CONTAINS'),
+          array('NON_ADMIN', 'CONTAINS'),
+        ),
+        'result' => array(
+          $users['non_admin']->uid => $user_labels['non_admin'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('invalid user', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+      array(
+        'arguments' => array(
+          array('blocked', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+    );
+    $this->assertReferencable($field, $referencable_tests, 'User handler');
+
+    $GLOBALS['user'] = $users['admin'];
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          $users['anonymous']->uid => $user_labels['anonymous'],
+          $users['admin']->uid => $user_labels['admin'],
+          $users['non_admin']->uid => $user_labels['non_admin'],
+          $users['blocked']->uid => $user_labels['blocked'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('blocked', 'CONTAINS'),
+        ),
+        'result' => array(
+          $users['blocked']->uid => $user_labels['blocked'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('Anonymous', 'CONTAINS'),
+          array('anonymous', 'CONTAINS'),
+        ),
+        'result' => array(
+          $users['anonymous']->uid => $user_labels['anonymous'],
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $referencable_tests, 'User handler (admin)');
+  }
+
+  /**
+   * Test the comment-specific overrides of the entity handler.
+   */
+  public function testCommentHandler() {
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'handler' => 'base',
+        'target_type' => 'comment',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+        ),
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entityreference',
+      'cardinality' => '1',
+    );
+
+    // Build a set of test data.
+    $node_values = array(
+      'published' => array(
+        'type' => 'article',
+        'status' => 1,
+        'title' => 'Node published',
+        'uid' => 1,
+      ),
+      'unpublished' => array(
+        'type' => 'article',
+        'status' => 0,
+        'title' => 'Node unpublished',
+        'uid' => 1,
+      ),
+    );
+    $nodes = array();
+    foreach ($node_values as $key => $values) {
+      $node = entity_create('node', $values);
+      $node->save();
+      $nodes[$key] = $node;
+    }
+
+    $comment_values = array(
+      'published_published' => array(
+        'nid' => $nodes['published']->nid,
+        'uid' => 1,
+        'cid' => NULL,
+        'pid' => 0,
+        'status' => COMMENT_PUBLISHED,
+        'subject' => 'Comment Published <&>',
+        'language' => LANGUAGE_NOT_SPECIFIED,
+      ),
+      'published_unpublished' => array(
+        'nid' => $nodes['published']->nid,
+        'uid' => 1,
+        'cid' => NULL,
+        'pid' => 0,
+        'status' => COMMENT_NOT_PUBLISHED,
+        'subject' => 'Comment Unpublished <&>',
+        'language' => LANGUAGE_NOT_SPECIFIED,
+      ),
+      'unpublished_published' => array(
+        'nid' => $nodes['unpublished']->nid,
+        'uid' => 1,
+        'cid' => NULL,
+        'pid' => 0,
+        'status' => COMMENT_NOT_PUBLISHED,
+        'subject' => 'Comment Published on Unpublished node <&>',
+        'language' => LANGUAGE_NOT_SPECIFIED,
+      ),
+    );
+
+    $comments = array();
+    $comment_labels = array();
+    foreach ($comment_values as $key => $values) {
+      $comment = entity_create('comment', $values);
+      $comment->save();
+      $comments[$key] = $comment;
+      $comment_labels[$key] = check_plain($comment->label());
+    }
+
+    // Test as a non-admin.
+    $normal_user = $this->drupalCreateUser(array('access content', 'access comments'));
+    $GLOBALS['user'] = $normal_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          $comments['published_published']->cid => $comment_labels['published_published'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('Published', 'CONTAINS'),
+        ),
+        'result' => array(
+          $comments['published_published']->cid => $comment_labels['published_published'],
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('invalid comment', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+      array(
+        'arguments' => array(
+          array('Comment Unpublished', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+    );
+    $this->assertReferencable($field, $referencable_tests, 'Comment handler');
+
+    // Test as a comment admin.
+    $admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments'));
+    $GLOBALS['user'] = $admin_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          $comments['published_published']->cid => $comment_labels['published_published'],
+          $comments['published_unpublished']->cid => $comment_labels['published_unpublished'],
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $referencable_tests, 'Comment handler (comment admin)');
+
+    // Test as a node and comment admin.
+    $admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments', 'bypass node access'));
+    $GLOBALS['user'] = $admin_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          $comments['published_published']->cid => $comment_labels['published_published'],
+          $comments['published_unpublished']->cid => $comment_labels['published_unpublished'],
+          $comments['unpublished_published']->cid => $comment_labels['unpublished_published'],
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $referencable_tests, 'Comment handler (comment + node admin)');
+  }
+}
