diff --git a/core/modules/field/modules/entity_reference/css/entity_reference-rtl.admin.css b/core/modules/field/modules/entity_reference/css/entity_reference-rtl.admin.css
new file mode 100644
index 0000000..3302ab8
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/css/entity_reference-rtl.admin.css
@@ -0,0 +1,4 @@
+
+.entity_reference-settings {
+ margin-right: 1.5em;
+}
diff --git a/core/modules/field/modules/entity_reference/css/entity_reference.admin.css b/core/modules/field/modules/entity_reference/css/entity_reference.admin.css
new file mode 100644
index 0000000..d608ccf
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/css/entity_reference.admin.css
@@ -0,0 +1,4 @@
+
+.entity_reference-settings {
+ margin-left: 1.5em; /* LTR */
+}
diff --git a/core/modules/field/modules/entity_reference/entity_reference.info b/core/modules/field/modules/entity_reference/entity_reference.info
new file mode 100644
index 0000000..2216092
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/entity_reference.info
@@ -0,0 +1,6 @@
+name = Entity Reference
+description = Provides a field that can reference other entities.
+package = Core
+version = VERSION
+core = 8.x
+dependencies[] = field
diff --git a/core/modules/field/modules/entity_reference/entity_reference.install b/core/modules/field/modules/entity_reference/entity_reference.install
new file mode 100644
index 0000000..efd1971
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/entity_reference.install
@@ -0,0 +1,48 @@
+ array(
+ 'target_id' => array(
+ 'description' => 'The ID of the target entity.',
+ 'type' => 'int',
+ 'unsigned' => TRUE,
+ 'not null' => TRUE,
+ ),
+ 'revision_id' => array(
+ 'description' => 'The revision ID of the target entity.',
+ 'type' => 'int',
+ 'unsigned' => TRUE,
+ 'not null' => FALSE,
+ ),
+ ),
+ 'indexes' => array(
+ 'target_id' => array('target_id'),
+ ),
+ 'foreign keys' => array(),
+ );
+
+ // Create a foreign key to the target entity type base type.
+ // @todo It's still not safe to call entity_get_info() in here..
+// $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/field/modules/entity_reference/entity_reference.module b/core/modules/field/modules/entity_reference/entity_reference.module
new file mode 100644
index 0000000..df3e3f3
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/entity_reference.module
@@ -0,0 +1,472 @@
+ t('Entity Reference'),
+ 'description' => t('This field reference another entity.'),
+ 'settings' => array(
+ // Default to a primary entity type (i.e. node or user).
+ 'target_type' => module_exists('node') ? 'node' : 'user',
+ ),
+ 'instance_settings' => array(
+ // The selection handler for this instance.
+ 'handler' => 'generic',
+ // The handler settings.
+ 'handler_settings' => array(),
+ ),
+ 'default_widget' => 'entity_reference_autocomplete',
+ 'default_formatter' => 'entity_reference_label',
+ );
+ return $field_info;
+}
+
+/**
+ * Implements hook_menu().
+ */
+function entity_reference_menu() {
+ $items = array();
+
+ $items['entity_reference/autocomplete/single/%/%/%'] = array(
+ 'title' => 'Entity Reference Autocomplete',
+ 'page callback' => 'entity_reference_autocomplete_callback',
+ 'page arguments' => array(2, 3, 4, 5),
+ 'access callback' => 'entity_reference_autocomplete_access_callback',
+ 'access arguments' => array(2, 3, 4, 5),
+ 'type' => MENU_CALLBACK,
+ );
+ $items['entity_reference/autocomplete/tags/%/%/%'] = array(
+ 'title' => 'Entity Reference Autocomplete',
+ 'page callback' => 'entity_reference_autocomplete_callback',
+ 'page arguments' => array(2, 3, 4, 5),
+ 'access callback' => 'entity_reference_autocomplete_access_callback',
+ 'access arguments' => array(2, 3, 4, 5),
+ 'type' => MENU_CALLBACK,
+ );
+
+ return $items;
+}
+
+/**
+ * Gets the selection handler for a given entity_reference field.
+ */
+function entity_reference_get_selection_handler($field, $instance, EntityInterface $entity = NULL) {
+ $options = array(
+ 'field' => $field,
+ 'instance' => $instance,
+ 'entity' => $entity,
+ );
+ return drupal_container()->get('plugin.manager.entity_reference.selection')->getInstance($options);
+}
+
+/**
+ * Implements hook_field_is_empty().
+ */
+function entity_reference_field_is_empty($item, $field) {
+ return !isset($item['target_id']) || !is_numeric($item['target_id']);
+}
+
+/**
+ * Implements hook_field_validate().
+ */
+function entity_reference_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
+ $ids = array();
+ foreach ($items as $delta => $item) {
+ if (!entity_reference_field_is_empty($item, $field) && $item['target_id'] !== NULL) {
+ $ids[$item['target_id']] = $delta;
+ }
+ }
+
+ if ($ids) {
+ $valid_ids = entity_reference_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' => 'entity_reference_invalid_entity',
+ 'message' => t('The referenced entity (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id)),
+ );
+ }
+ }
+ }
+}
+
+/**
+ * Implements hook_field_settings_form().
+ */
+function entity_reference_field_settings_form($field, $instance, $has_data) {
+ // 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,
+ );
+
+ return $form;
+}
+
+/**
+ * Implements hook_field_instance_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 entity_reference_field_instance_settings_form($field, $instance) {
+ $form['entity_reference_wrapper'] = array(
+ '#type' => 'container',
+ '#attached' => array(
+ 'css' => array(drupal_get_path('module', 'entity_reference') . '/css/entity_reference.admin.css'),
+ ),
+ '#process' => array(
+ '_entity_reference_field_instance_settings_process',
+ '_entity_reference_field_instance_settings_ajax_process',
+ ),
+ '#element_validate' => array('_entity_reference_field_instance_settings_validate'),
+ '#field' => $field,
+ '#instance' => $instance->definition,
+ );
+ return $form;
+}
+
+/**
+ * Render API callback: Processes the field settings form and allows access to
+ * the form state.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function _entity_reference_field_instance_settings_process($form, $form_state) {
+ $field = isset($form_state['entity_reference']['field']) ? $form_state['entity_reference']['field'] : $form['#field'];
+ $instance = isset($form_state['entity_reference']['instance']) ? $form_state['entity_reference']['instance'] : $form['#instance'];
+
+ $settings = $instance['settings'];
+ $settings += array('handler' => 'generic');
+
+ // Get all selection plugins for this entity type.
+ $selection_plugins = drupal_container()->get('plugin.manager.entity_reference.selection')->getSelectionGroups($field['settings']['target_type']);
+ $handler_groups = array_keys($selection_plugins);
+
+ $handlers = drupal_container()->get('plugin.manager.entity_reference.selection')->getDefinitions();
+ $handlers_options = array();
+ foreach ($handlers as $plugin_id => $plugin) {
+ // We only display base plugins (e.g. 'generic', 'views', ..) and not entity
+ // type specific plugins (e.g. 'generic_node', 'generic_user', ...).
+ if (in_array($plugin_id, $handler_groups)) {
+ $handlers_options[$plugin_id] = check_plain($plugin['label']);
+ }
+ }
+
+ $form['handler'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Entity selection'),
+ '#tree' => TRUE,
+ '#process' => array('_entity_reference_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']['handler_submit'] = array(
+ '#type' => 'submit',
+ '#value' => t('Change handler'),
+ '#limit_validation_errors' => array(),
+ '#attributes' => array(
+ 'class' => array('js-hide'),
+ ),
+ '#submit' => array('entity_reference_settings_ajax_submit'),
+ );
+
+ $form['handler']['handler_settings'] = array(
+ '#type' => 'container',
+ '#attributes' => array('class' => array('entity_reference-settings')),
+ );
+
+ $handler = entity_reference_get_selection_handler($field, $instance);
+ $form['handler']['handler_settings'] += $handler->settingsForm($field, $instance);
+
+ return $form;
+}
+
+/**
+ * Render API callback: Processes the field instance settings form and allows
+ * access to the form state.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function _entity_reference_field_instance_settings_ajax_process($form, $form_state) {
+ _entity_reference_field_instance_settings_ajax_process_element($form, $form);
+ return $form;
+}
+
+/**
+ * Adds entity_reference specific properties to AJAX form elements from the
+ * field instance settings form.
+ *
+ * @see _entity_reference_field_instance_settings_ajax_process()
+ */
+function _entity_reference_field_instance_settings_ajax_process_element(&$element, $main_form) {
+ if (isset($element['#ajax']) && $element['#ajax'] === TRUE) {
+ $element['#ajax'] = array(
+ 'callback' => 'entity_reference_settings_ajax',
+ 'wrapper' => $main_form['#id'],
+ 'element' => $main_form['#array_parents'],
+ );
+ }
+
+ foreach (element_children($element) as $key) {
+ _entity_reference_field_instance_settings_ajax_process_element($element[$key], $main_form);
+ }
+}
+
+/**
+ * Render API callback: Moves entity_reference specific Form API elements
+ * (i.e. 'handler_settings') up a level for easier processing by the validation
+ * and submission handlers.
+ *
+ * @see _entity_reference_field_settings_process()
+ */
+function _entity_reference_form_process_merge_parent($element) {
+ $parents = $element['#parents'];
+ array_pop($parents);
+ // For the 'Entity selection' fieldset, we need to go one more level above
+ // because of our extra container.
+ if (isset($element['#title']) && $element['#title'] == t('Entity selection')) {
+ array_pop($parents);
+ }
+ $element['#parents'] = $parents;
+ return $element;
+}
+
+/**
+ * Form element validation handler; Filters the #value property of an element.
+ */
+function _entity_reference_element_validate_filter(&$element, &$form_state) {
+ $element['#value'] = array_filter($element['#value']);
+ form_set_value($element, $element['#value'], $form_state);
+}
+
+/**
+ * Form element validation handler; Stores the new values in the form state.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function _entity_reference_field_instance_settings_validate($form, &$form_state) {
+ $instance = $form['#instance'];
+ if (isset($form_state['values']['instance'])) {
+ $instance['settings'] = $form_state['values']['instance']['settings'];
+ }
+ $form_state['entity_reference']['instance'] = $instance;
+
+ unset($form_state['values']['instance']['settings']['handler_submit']);
+}
+
+/**
+ * Ajax callback for the handler settings form.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function entity_reference_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 entity_reference_field_instance_settings_form()
+ */
+function entity_reference_settings_ajax_submit($form, &$form_state) {
+ $form_state['rebuild'] = TRUE;
+}
+
+/**
+ * Implements hook_options_list().
+ */
+function entity_reference_options_list($field, $instance, $entity_type = NULL, $entity = NULL) {
+ if (!$options = entity_reference_get_selection_handler($field, $instance, $entity)->getReferencableEntities()) {
+ return array();
+ }
+
+ // Rebuild the array by changing the bundle key into the bundle label.
+ $target_type = $field['settings']['target_type'];
+ $entity_info = entity_get_info($target_type);
+
+ $return = array();
+ foreach ($options as $bundle => $entity_ids) {
+ $bundle_label = check_plain($entity_info['bundles'][$bundle]['label']);
+ $return[$bundle_label] = $entity_ids;
+ }
+
+ return count($return) == 1 ? reset($return) : $return;
+}
+
+/**
+ * Implements hook_query_TAG_alter().
+ */
+function entity_reference_query_entity_reference_alter(AlterableInterface $query) {
+ $handler = $query->getMetadata('entity_reference_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 entity_reference_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'] != 'entity_reference' || !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.
+ *
+ * @return \Symfony\Component\HttpFoundation\JsonResponse
+ */
+function entity_reference_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);
+
+ return entity_reference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
+}
+
+/**
+ * Returns JSON data based on a given field, instance and search string.
+ *
+ * This function can be used by other modules that wish to pass a mocked
+ * definition of the field on instance.
+ *
+ * @param string $type
+ * The widget type (i.e. 'single' or 'tags').
+ * @param array $field
+ * The field array definition.
+ * @param array $instance
+ * The instance array definition.
+ * @param string $entity_type
+ * The entity type.
+ * @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.
+ *
+ * @return \Symfony\Component\HttpFoundation\JsonResponse
+ *
+ * @see entity_reference_autocomplete_callback()
+ */
+function entity_reference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
+ $target_type = $field['settings']['target_type'];
+ $matches = array();
+ $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 = entity_reference_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 $values) {
+ foreach ($values 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] = '
' . $label . '
';
+ }
+ }
+ }
+
+ return new JsonResponse($matches);
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceRecursiveRenderingException.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceRecursiveRenderingException.php
new file mode 100644
index 0000000..a6f6c32
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceRecursiveRenderingException.php
@@ -0,0 +1,14 @@
+register('plugin.manager.entity_reference.selection', 'Drupal\entity_reference\Plugin\Type\SelectionPluginManager');
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionGeneric.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionGeneric.php
new file mode 100644
index 0000000..f8519ec
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionGeneric.php
@@ -0,0 +1,54 @@
+derivatives) && !empty($this->derivatives[$derivative_id])) {
+ return $this->derivatives[$derivative_id];
+ }
+ $this->getDerivativeDefinitions($base_plugin_definition);
+ return $this->derivatives[$derivative_id];
+ }
+
+ /**
+ * Implements DerivativeInterface::getDerivativeDefinitions().
+ */
+ public function getDerivativeDefinitions(array $base_plugin_definition) {
+ $supported_entities = array(
+ 'comment',
+ 'file',
+ 'node',
+ 'taxonomy_term',
+ 'user'
+ );
+ foreach (entity_get_info() as $entity_type => $info) {
+ if (!in_array($entity_type, $supported_entities)) {
+ $this->derivatives[$entity_type] = $base_plugin_definition;
+ $this->derivatives[$entity_type]['label'] = t('@enitty_type selection', array('@entity_type' => $info['label']));
+ }
+ }
+ return $this->derivatives;
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php
new file mode 100644
index 0000000..2f09cb5
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php
@@ -0,0 +1,65 @@
+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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php
new file mode 100644
index 0000000..05a11c5
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php
@@ -0,0 +1,79 @@
+baseDiscovery = new AlterDecorator(new AnnotatedClassDiscovery('entity_reference', 'selection'), 'entity_reference_selection');
+ $this->discovery = new CacheDecorator($this->baseDiscovery, 'entity_reference_selection');
+ $this->factory = new ReflectionFactory($this);
+ }
+
+ /**
+ * Overrides Drupal\Component\Plugin\PluginManagerBase::createInstace().
+ */
+ public function createInstance($plugin_id, array $configuration = array()) {
+ // We want to provide a broken handler class whenever a class is not found.
+ try {
+ return parent::createInstance($plugin_id, $configuration);
+ }
+ catch (PluginException $e) {
+ return new SelectionBroken($configuration['field'], $configuration['instance']);
+ }
+ }
+
+ /**
+ * Overrides Drupal\Component\Plugin\PluginManagerBase::getInstance().
+ */
+ public function getInstance(array $options) {
+ $selection_handler = $options['instance']['settings']['handler'];
+ $target_entity_type = $options['field']['settings']['target_type'];
+
+ // Get all available selection plugins for this entity type.
+ $selection_handler_groups = $this->getSelectionGroups($target_entity_type);
+
+ // Sort the selection plugins by weight and select the best match.
+ uasort($selection_handler_groups[$selection_handler], 'drupal_sort_weight');
+ end($selection_handler_groups[$selection_handler]);
+ $plugin_id = key($selection_handler_groups[$selection_handler]);
+
+ return $this->createInstance($plugin_id, $options);
+ }
+
+ /**
+ * Returns a list of selection plugins that can reference a specific entity
+ * type.
+ *
+ * @param string $entity_type
+ * A Drupal entity type.
+ *
+ * @return array
+ * An array of selection plugins grouped by selection group.
+ */
+ public function getSelectionGroups($entity_type) {
+ $plugins = array();
+
+ foreach ($this->getDefinitions() as $plugin_id => $plugin) {
+ if (!isset($plugin['entity_types']) || in_array($entity_type, $plugin['entity_types'])) {
+ $plugins[$plugin['group']][$plugin_id] = $plugin;
+ }
+ }
+
+ return $plugins;
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Comment.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Comment.php
new file mode 100644
index 0000000..ec93709
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Comment.php
@@ -0,0 +1,72 @@
+getTables();
+ $base_table = $tables['base_table']['alias'];
+ if (!user_access('administer comments')) {
+ $query->condition("$base_table.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.
+ $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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/File.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/File.php
new file mode 100644
index 0000000..858645c
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/File.php
@@ -0,0 +1,43 @@
+getTables();
+ $base_table = $tables['base_table']['alias'];
+ $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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Node.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Node.php
new file mode 100644
index 0000000..b5dd021
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Node.php
@@ -0,0 +1,44 @@
+getTables();
+ $base_table = $tables['base_table']['alias'];
+ $query->condition("$base_table.status", NODE_PUBLISHED);
+ }
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionGeneric.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionGeneric.php
new file mode 100644
index 0000000..2ef58a9
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionGeneric.php
@@ -0,0 +1,311 @@
+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.
+ if (!isset($instance['settings']['handler_settings'])) {
+ $instance['settings']['handler_settings'] = array();
+ }
+ $instance['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' => $instance['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('_entity_reference_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' => $instance['settings']['handler_settings']['sort']['type'],
+ );
+
+ $form['sort']['settings'] = array(
+ '#type' => 'container',
+ '#attributes' => array('class' => array('entity_reference-settings')),
+ '#process' => array('_entity_reference_form_process_merge_parent'),
+ );
+
+ if ($instance['settings']['handler_settings']['sort']['type'] == 'property') {
+ // Merge-in default values.
+ $instance['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' => $instance['settings']['handler_settings']['sort']['property'],
+ );
+ }
+ elseif ($instance['settings']['handler_settings']['sort']['type'] == 'field') {
+ // Merge-in default values.
+ $instance['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' => $instance['settings']['handler_settings']['sort']['field'],
+ );
+ }
+
+ if ($instance['settings']['handler_settings']['sort']['type'] != 'none') {
+ // Merge-in default values.
+ $instance['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' => $instance['settings']['handler_settings']['sort']['direction'],
+ );
+ }
+
+ return $form;
+ }
+
+ /**
+ * Implements SelectionInterface::getReferencableEntities().
+ */
+ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+ $target_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)) {
+ return array();
+ }
+
+ $options = array();
+ $entities = entity_load_multiple($target_type, $result);
+ foreach ($entities as $entity_id => $entity) {
+ $bundle = $entity->bundle();
+ $options[$bundle][$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) {
+ $result = array();
+ if ($ids) {
+ $target_type = $this->field['settings']['target_type'];
+ $entity_info = entity_get_info($target_type);
+ $query = $this->buildEntityFieldQuery();
+ $result = $query
+ ->condition($entity_info['entity_keys']['id'], $ids, 'IN')
+ ->execute();
+ }
+
+ return $result;
+ }
+
+ /**
+ * 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') {
+ $target_type = $this->field['settings']['target_type'];
+ $entity_info = entity_get_info($target_type);
+
+ $query = entity_query($target_type);
+ if (!empty($this->instance['settings']['handler_settings']['target_bundles'])) {
+ $bundle_key = $entity_info['entity_keys']['bundle'];
+ $query->condition($bundle_key, $this->instance['settings']['handler_settings']['target_bundles'], 'IN');
+ }
+
+ if (isset($match) && isset($entity_info['entity_keys']['label'])) {
+ $query->condition($entity_info['entity_keys']['label'], $match, $match_operator);
+ }
+
+ // Add entity-access tag.
+ $query->addTag($this->field['settings']['target_type'] . '_access');
+
+ // Add the Selection handler for
+ // entity_reference_query_entity_reference_alter()
+ $query->addTag('entity_reference');
+ $query->addMetaData('field', $this->field);
+ $query->addMetaData('entity_reference_selection_handler', $this);
+
+ // Add the sort option.
+ if (!empty($this->instance['settings']['handler_settings']['sort'])) {
+ $sort_settings = $this->instance['settings']['handler_settings']['sort'];
+ if ($sort_settings['type'] == 'property') {
+ $query->condition($sort_settings['property'], $sort_settings['direction']);
+ }
+ elseif ($sort_settings['type'] == 'field') {
+ list($field, $column) = explode(':', $sort_settings['field'], 2);
+ $query->sort("$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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Term.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Term.php
new file mode 100644
index 0000000..7b8cbc8
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/Term.php
@@ -0,0 +1,81 @@
+getTables();
+ $base_table = $tables['base_table']['alias'];
+ $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;
+ }
+ }
+ }
+
+ /**
+ * Overrides SelectionBase::getReferencableEntities().
+ */
+ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+ if ($match || $limit) {
+ return parent::getReferencableEntities($match , $match_operator, $limit);
+ }
+
+ $options = array();
+
+ // We imitate core by calling taxonomy_get_tree().
+ $entity_info = entity_get_info('taxonomy_term');
+ $bundles = !empty($this->instance['settings']['handler_settings']['target_bundles']) ? $this->instance['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']);
+
+ foreach ($bundles as $bundle) {
+ if ($vocabulary = taxonomy_vocabulary_machine_name_load($bundle)) {
+ if ($terms = taxonomy_get_tree($vocabulary->vid, 0)) {
+ foreach ($terms as $term) {
+ $options[$vocabulary->machine_name][$term->tid] = str_repeat('-', $term->depth) . check_plain($term->name);
+ }
+ }
+ }
+ }
+
+ return $options;
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/User.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/User.php
new file mode 100644
index 0000000..8effa95
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/User.php
@@ -0,0 +1,85 @@
+condition('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->condition('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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
new file mode 100644
index 0000000..bc811ca
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
@@ -0,0 +1,113 @@
+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;
+ }
+
+ /**
+ * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::settingsSummary().
+ */
+ 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('
', $summary);
+ }
+
+ /**
+ * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+ */
+ public function viewElements(EntityInterface $entity, $langcode, array $items) {
+ // Remove un-accessible items.
+ parent::viewElements($entity, $langcode, $items);
+
+ $view_mode = $this->getSetting('view_mode');
+ $links = $this->getSetting('links');
+
+ $target_type = $this->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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php
new file mode 100644
index 0000000..2ecaaad
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php
@@ -0,0 +1,101 @@
+ $entity) {
+ foreach ($items[$id] as $delta => $item) {
+ if (!empty($item['revision_id'])) {
+ $revision_ids[] = $item['revision_id'];
+ }
+ elseif (!empty($item['target_id'])) {
+ $target_ids[] = $item['target_id'];
+ }
+ }
+ }
+
+ $target_type = $this->field['settings']['target_type'];
+
+ $target_entities = array();
+
+ if ($target_ids) {
+ $target_entities = entity_load_multiple($target_type, $target_ids);
+ }
+
+ if ($revision_ids) {
+ // We need to load the revisions one by-one.
+ foreach ($revision_ids as $revision_id) {
+ $entity = entity_revision_load($target_type, $revision_id);
+ // Use the revision-ID in the key.
+ $identifier = $entity->id() . ':' . $revision_id;
+ $target_entities[$identifier] = $entity;
+ }
+ }
+
+ // Iterate through the fieldable entities again to attach the loaded data.
+ foreach ($entities as $id => $entity) {
+
+ foreach ($items[$id] as $delta => $item) {
+ // If we have a revision-ID, the key uses it as-well.
+ $identifier = !empty($item['revision_id']) ? $item['target_id'] . ':' . $item['revision_id'] : $item['target_id'];
+ if (!isset($target_entities[$identifier])) {
+ continue;
+ }
+
+ $items[$id][$delta]['entity'] = $target_entities[$identifier];
+
+ $entity = $target_entities[$identifier];
+
+ // 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;
+ }
+ }
+ }
+
+ /**
+ * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::viewElements().
+ *
+ * @see Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::prepareView().
+ */
+ public function viewElements(EntityInterface $entity, $langcode, array $items) {
+ // Remove un-accessible items.
+ foreach ($items as $delta => $item) {
+ if (empty($item['access'])) {
+ unset($items[$delta]);
+ }
+ }
+ return array();
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php
new file mode 100644
index 0000000..033f1cf
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php
@@ -0,0 +1,42 @@
+ $item) {
+ $elements[$delta] = array('#markup' => check_plain($item['target_id']));
+ }
+
+ return $elements;
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
new file mode 100644
index 0000000..0464bb8
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
@@ -0,0 +1,80 @@
+ t('Link label to the referenced entity'),
+ '#type' => 'checkbox',
+ '#default_value' => $this->getSetting('link'),
+ );
+
+ return $elements;
+ }
+
+ /**
+ * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::settingsSummary().
+ */
+ public function settingsSummary() {
+ $summary = array();
+ $summary[] = $this->getSetting('link') ? t('Link to the referenced entity') : t('No link');
+
+ return implode('
', $summary);
+ }
+
+ /**
+ * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+ */
+ public function viewElements(EntityInterface $entity, $langcode, array $items) {
+ // Remove un-accessible items.
+ parent::viewElements($entity, $langcode, $items);
+
+ $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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php
new file mode 100644
index 0000000..56d84d1
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php
@@ -0,0 +1,75 @@
+prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entity_reference/autocomplete/tags');
+ }
+
+ /**
+ * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate()
+ */
+ public function elementValidate($element, &$form_state, $form) {
+ $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.
+ $handler = entity_reference_get_selection_handler($this->field, $this->instance);
+ $value[] = array(
+ 'target_id' => $handler->validateAutocompleteInput($entity, $element, $form_state, $form),
+ );
+ }
+ }
+ }
+ form_set_value($element, $value, $form_state);
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php
new file mode 100644
index 0000000..cf64838
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php
@@ -0,0 +1,76 @@
+prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entity_reference/autocomplete/single');
+ return array('target_id' => $element);
+ }
+
+ /**
+ * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate()
+ */
+ public function elementValidate($element, &$form_state, $form) {
+ // 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.
+ $handler = entity_reference_get_selection_handler($this->field, $this->instance);
+ $value = $handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form);
+ }
+ }
+ form_set_value($element, $value, $form_state);
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php
new file mode 100644
index 0000000..5d0bb89
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php
@@ -0,0 +1,126 @@
+ '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 Contains can cause performance issues on sites with thousands of nodes.'),
+ );
+ $element['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 $element;
+ }
+
+ /**
+ * 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, 'entity_reference/autocomplete/single');
+ return array('target_id' => $element);
+ }
+
+ /**
+ * Prepares the element.
+ */
+ 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 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;
+ }
+
+ /**
+ * Overrides Drupal\field\Plugin\Type\Widget\WidgetBase::errorElement().
+ */
+ public function errorElement(array $element, array $error, array $form, array &$form_state) {
+ return $element['target_id'];
+ }
+
+ /**
+ * Validates an element.
+ */
+ public function elementValidate($element, &$form_state, $form) { }
+
+ /**
+ * Gets the entity labels.
+ */
+ protected function getLabels(array $items) {
+ $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($this->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/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php
new file mode 100644
index 0000000..40334a3
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php
@@ -0,0 +1,166 @@
+ 'entity_reference');
+ $options['defaults']['default']['style'] = FALSE;
+ $options['row']['contains']['type'] = array('default' => 'entity_reference');
+ $options['defaults']['default']['row'] = FALSE;
+
+ // Make sure the query is not cached.
+ $options['defaults']['default']['cache'] = FALSE;
+
+ // Set the display title to an empty string (not used in this display type).
+ $options['title']['default'] = '';
+ $options['defaults']['default']['title'] = FALSE;
+
+ return $options;
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::getStyleType().
+ */
+ protected function getStyleType() {
+ return 'entity_reference';
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::execute().
+ */
+ public function execute() {
+ return $this->view->render($this->display['id']);
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::render().
+ */
+ public function render() {
+ if (!empty($this->view->result) || !empty($this->view->style_plugin->definition['even empty'])) {
+ return $this->view->style_plugin->render($this->view->result);
+ }
+ return '';
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::usesExposed().
+ */
+ public function usesExposed() {
+ return FALSE;
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::query().
+ */
+ public function query() {
+ $options = $this->getOption('entity_reference_options');
+
+ // Play nice with Views UI 'preview' : if the view is not executed through
+ // EntityReference_SelectionHandler_Views::getReferencableEntities(),
+ // don't alter the query.
+ if (empty($options)) {
+ return;
+ }
+
+ // Make sure the id field is included in the results, and save its alias
+ // so that references_plugin_style can retrieve it.
+ $this->id_field_alias = $id_field = $this->view->query->add_field($this->view->storage->base_table, $this->view->storage->base_field);
+ if (strpos($id_field, '.') === FALSE) {
+ $id_field = $this->view->storage->base_table . '.' . $this->id_field_alias;
+ }
+
+ // Restrict the autocomplete options based on what's been typed already.
+ if (isset($options['match'])) {
+ $style_options = $this->getOption('style');
+ $value = db_like($options['match']) . '%';
+ if ($options['match_operator'] != 'STARTS_WITH') {
+ $value = '%' . $value;
+ }
+
+ // Multiple search fields are OR'd together
+ $conditions = db_or();
+
+ // Build the condition using the selected search fields
+ foreach ($style_options['options']['search_fields'] as $field_alias) {
+ if (!empty($field_alias)) {
+ // Get the table and field names for the checked field
+ $field = $this->view->query->fields[$this->view->field[$field_alias]->field_alias];
+ // Add an OR condition for the field
+ $conditions->condition($field['table'] . '.' . $field['field'], $value, 'LIKE');
+ }
+ }
+
+ $this->view->query->add_where(0, $conditions);
+ }
+
+ // Add an IN condition for validation.
+ if (!empty($options['ids'])) {
+ $this->view->query->add_where(0, $id_field, $options['ids']);
+ }
+
+ $this->view->setItemsPerPage($options['limit']);
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::validate().
+ */
+ public function validate() {
+ $errors = parent::validate();
+ // Verify that search fields are set up.
+ $style = $this->getOption('style');
+ if (!isset($style['options']['search_fields'])) {
+ $errors[] = t('Display "@display" needs a selected search fields to work properly. See the settings for the Entity Reference list format.', array('@display' => $this->display['display_title']));
+ }
+ else {
+ // Verify that the search fields used actually exist.
+ //$fields = array_keys($this->view->get_items('field'));
+ $fields = array_keys($this->handlers['field']);
+ foreach ($style['options']['search_fields'] as $field_alias => $enabled) {
+ if ($enabled && !in_array($field_alias, $fields)) {
+ $errors[] = t('Display "@display" uses field %field as search field, but the field is no longer present. See the settings for the Entity Reference list format.', array('@display' => $this->display['display_title'], '%field' => $field_alias));
+ }
+ }
+ }
+ return $errors;
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php
new file mode 100644
index 0000000..9856911
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php
@@ -0,0 +1,61 @@
+ '-');
+
+ return $options;
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\row\Fields::buildOptionsForm().
+ */
+ public function buildOptionsForm(&$form, &$form_state) {
+ parent::buildOptionsForm($form, $form_state);
+
+ // Expand the description of the 'Inline field' checkboxes.
+ $form['inline']['#description'] .= '
' . t("Note: In 'Entity Reference' displays, all fields will be displayed inline unless an explicit selection of inline fields is made here." );
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\row\Fields::pre_render().
+ */
+ public function pre_render($row) {
+ // Force all fields to be inline by default.
+ if (empty($this->options['inline'])) {
+ $fields = $this->view->getItems('field', $this->displayHandler->display['id']);
+ $this->options['inline'] = drupal_map_assoc(array_keys($fields));
+ }
+
+ return parent::pre_render($row);
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php
new file mode 100644
index 0000000..e8f6857
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php
@@ -0,0 +1,105 @@
+ NULL);
+
+ return $options;
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::buildOptionsForm().
+ */
+ public function buildOptionsForm(&$form, &$form_state) {
+ parent::buildOptionsForm($form, $form_state);
+ $options = array();
+
+ if (isset($form['grouping'])) {
+ $options = $form['grouping'][0]['field']['#options'];
+ unset($options['']);
+ $form['search_fields'] = array(
+ '#type' => 'checkboxes',
+ '#title' => t('Search fields'),
+ '#options' => $options,
+ '#required' => TRUE,
+ '#default_value' => $this->options['search_fields'],
+ '#description' => t('Select the field(s) that will be searched when using the autocomplete widget.'),
+ '#weight' => -3,
+ );
+ }
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::render().
+ */
+ public function render() {
+ $options = $this->displayHandler->getOption('entity_reference_options');
+
+ // Play nice with Views UI 'preview': if the view is not executed through
+ // Drupal\views\Plugin\entity_reference\selection\Views::getReferencableEntities(),
+ // just display the HTML.
+ if (empty($options)) {
+ return parent::render();
+ }
+
+ // Group the rows according to the grouping field, if specified.
+ $sets = $this->render_grouping($this->view->result, $this->options['grouping']);
+
+ // Grab the alias of the 'id' field added by entity_reference_plugin_display.
+ $id_field_alias = $this->displayHandler->id_field_alias;
+
+ // @todo We don't display grouping info for now. Could be useful for select
+ // widget, though.
+ $results = array();
+ $this->view->row_index = 0;
+ foreach ($sets as $records) {
+ foreach ($records as $values) {
+ // Sanitize html, remove line breaks and extra whitespace.
+ $results[$values->{$id_field_alias}] = filter_xss_admin(preg_replace('/\s\s+/', ' ', str_replace("\n", '', $this->row_plugin->render($values))));
+ $this->view->row_index++;
+ }
+ }
+ unset($this->view->row_index);
+ return $results;
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::even_empty().
+ */
+ function even_empty() {
+ return TRUE;
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAdminTest.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAdminTest.php
new file mode 100644
index 0000000..dba7111
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAdminTest.php
@@ -0,0 +1,119 @@
+ 'Entity Reference UI',
+ 'description' => 'Tests for the administrative UI.',
+ 'group' => 'Entity Reference',
+ );
+ }
+
+ public static $modules = array('field_ui', 'entity_reference');
+
+ 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]' => 'entity_reference',
+ 'fields[_add_new_field][widget_type]' => 'entity_reference_autocomplete',
+ ), t('Save'));
+
+ // Node should be selected by default.
+ $this->assertFieldByName('field[settings][target_type]', 'node');
+
+ // Second step: 'Instance settings' form.
+ $this->drupalPost(NULL, array(), t('Save field settings'));
+
+ // The base handler should be selected by default.
+ $this->assertFieldByName('instance[settings][handler]', 'generic');
+
+ // 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('instance[settings][handler_settings][target_bundles][' . $bundle_name . ']');
+ }
+
+ // Test the sort settings.
+ $options = array('none', 'property', 'field');
+ $this->assertFieldSelectOptions('instance[settings][handler_settings][sort][type]', $options);
+ // Option 0: no sort.
+ $this->assertFieldByName('instance[settings][handler_settings][sort][type]', 'none');
+ $this->assertNoFieldByName('instance[settings][handler_settings][sort][property]');
+ $this->assertNoFieldByName('instance[settings][handler_settings][sort][field]');
+ $this->assertNoFieldByName('instance[settings][handler_settings][sort][direction]');
+ // Option 1: sort by property.
+ $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][type]' => 'property'), 'instance[settings][handler_settings][sort][type]');
+ $this->assertFieldByName('instance[settings][handler_settings][sort][property]', '');
+ $this->assertNoFieldByName('instance[settings][handler_settings][sort][field]');
+ $this->assertFieldByName('instance[settings][handler_settings][sort][direction]', 'ASC');
+ // Option 2: sort by field.
+ $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][type]' => 'field'), 'instance[settings][handler_settings][sort][type]');
+ $this->assertNoFieldByName('instance[settings][handler_settings][sort][property]');
+ $this->assertFieldByName('instance[settings][handler_settings][sort][field]', '');
+ $this->assertFieldByName('instance[settings][handler_settings][sort][direction]', 'ASC');
+ // Set back to no sort.
+ $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][type]' => 'none'), 'instance[settings][handler_settings][sort][type]');
+
+ // 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/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php
new file mode 100644
index 0000000..4b7f594
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php
@@ -0,0 +1,497 @@
+ 'Entity Reference Handlers',
+ 'description' => 'Tests for the generic handlers provided by Entity Reference.',
+ 'group' => 'Entity Reference',
+ );
+ }
+
+ public static $modules = array('node', 'comment', 'entity_reference');
+
+ function setUp() {
+ parent::setUp();
+
+ // Create an Article node type.
+ if ($this->profile != 'standard') {
+ $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
+ }
+ }
+
+ protected function assertReferencable($field, $instance, $tests, $handler_name) {
+ $handler = entity_reference_get_selection_handler($field, $instance);
+
+ foreach ($tests as $test) {
+ foreach ($test['arguments'] as $arguments) {
+ $result = call_user_func_array(array($handler, 'getReferencableEntities'), $arguments);
+ $this->assertEqual($result, $test['result'], format_string('Valid result set returned by @handler.', array('@handler' => $handler_name)));
+
+ $result = call_user_func_array(array($handler, 'countReferencableEntities'), $arguments);
+ if (!empty($test['result'])) {
+ $bundle = key($test['result']);
+ $count = count($test['result'][$bundle]);
+ }
+ else {
+ $count = 0;
+ }
+
+ $this->assertEqual($result, $count, format_string('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(
+ 'target_type' => 'node',
+ ),
+ 'field_name' => 'test_field',
+ 'type' => 'entity_reference',
+ 'cardinality' => '1',
+ );
+ $instance = array(
+ 'settings' => array(
+ 'handler' => 'generic',
+ 'handler_settings' => array(
+ 'target_bundles' => array(),
+ ),
+ ),
+ );
+
+ // 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(
+ 'article' => array(
+ $nodes['published1']->nid => $node_labels['published1'],
+ $nodes['published2']->nid => $node_labels['published2'],
+ ),
+ ),
+ ),
+ array(
+ 'arguments' => array(
+ array('published1', 'CONTAINS'),
+ array('Published1', 'CONTAINS'),
+ ),
+ 'result' => array(
+ 'article' => array(
+ $nodes['published1']->nid => $node_labels['published1'],
+ ),
+ ),
+ ),
+ array(
+ 'arguments' => array(
+ array('published2', 'CONTAINS'),
+ array('Published2', 'CONTAINS'),
+ ),
+ 'result' => array(
+ 'article' => 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, $instance, $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(
+ 'article' => 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(
+ 'article' => array(
+ $nodes['unpublished']->nid => $node_labels['unpublished'],
+ ),
+ ),
+ ),
+ );
+ $this->assertReferencable($field, $instance, $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(
+ 'target_type' => 'user',
+ ),
+ 'field_name' => 'test_field',
+ 'type' => 'entity_reference',
+ 'cardinality' => '1',
+ );
+ $instance = array(
+ 'settings' => array(
+ 'handler' => 'generic',
+ 'handler_settings' => array(
+ 'target_bundles' => array(),
+ ),
+ ),
+ );
+
+ // 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(
+ 'user' => 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(
+ 'user' => 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, $instance, $referencable_tests, 'User handler');
+
+ $GLOBALS['user'] = $users['admin'];
+ $referencable_tests = array(
+ array(
+ 'arguments' => array(
+ array(NULL, 'CONTAINS'),
+ ),
+ 'result' => array(
+ 'user' => 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(
+ 'user' => array(
+ $users['blocked']->uid => $user_labels['blocked'],
+ ),
+ ),
+ ),
+ array(
+ 'arguments' => array(
+ array('Anonymous', 'CONTAINS'),
+ array('anonymous', 'CONTAINS'),
+ ),
+ 'result' => array(
+ 'user' => array(
+ $users['anonymous']->uid => $user_labels['anonymous'],
+ ),
+ ),
+ ),
+ );
+ $this->assertReferencable($field, $instance, $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(
+ 'target_type' => 'comment',
+ ),
+ 'field_name' => 'test_field',
+ 'type' => 'entity_reference',
+ 'cardinality' => '1',
+ );
+ $instance = array(
+ 'settings' => array(
+ 'handler' => 'generic',
+ 'handler_settings' => array(
+ 'target_bundles' => array(),
+ ),
+ ),
+ );
+
+ // 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(
+ 'comment_node_article' => array(
+ $comments['published_published']->cid => $comment_labels['published_published'],
+ ),
+ ),
+ ),
+ array(
+ 'arguments' => array(
+ array('Published', 'CONTAINS'),
+ ),
+ 'result' => array(
+ 'comment_node_article' => 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, $instance, $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(
+ 'comment_node_article' => array(
+ $comments['published_published']->cid => $comment_labels['published_published'],
+ $comments['published_unpublished']->cid => $comment_labels['published_unpublished'],
+ ),
+ ),
+ ),
+ );
+ $this->assertReferencable($field, $instance, $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(
+ 'comment_node_article' => 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, $instance, $referencable_tests, 'Comment handler (comment + node admin)');
+ }
+}
diff --git a/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php
new file mode 100644
index 0000000..5e94274
--- /dev/null
+++ b/core/modules/field/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php
@@ -0,0 +1,151 @@
+ 'Entity Reference handlers sort',
+ 'description' => 'Test sorting referenced items.',
+ 'group' => 'Entity Reference',
+ );
+ }
+
+ public static $modules = array('node', 'entity_reference');
+
+ function setUp() {
+ parent::setUp();
+
+ // Create an Article node type.
+ if ($this->profile != 'standard') {
+ $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
+ }
+ }
+
+ /**
+ * Assert sorting by field and property.
+ */
+ public function testSort() {
+ // Add text field to entity, to sort by.
+ $field_info = array(
+ 'field_name' => 'field_text',
+ 'type' => 'text',
+ 'entity_types' => array('node'),
+ );
+ field_create_field($field_info);
+
+ $instance_info = array(
+ 'label' => 'Text Field',
+ 'field_name' => 'field_text',
+ 'entity_type' => 'node',
+ 'bundle' => 'article',
+ 'settings' => array(),
+ 'required' => FALSE,
+ );
+ field_create_instance($instance_info);
+
+
+ // Build a fake field instance.
+ $field = array(
+ 'translatable' => FALSE,
+ 'entity_types' => array(),
+ 'settings' => array(
+ 'target_type' => 'node',
+ ),
+ 'field_name' => 'test_field',
+ 'type' => 'entityreference',
+ 'cardinality' => '1',
+ );
+
+ $instance = array(
+ 'settings' => array(
+ 'handler' => 'generic',
+ 'handler_settings' => array(
+ 'target_bundles' => array(),
+ // Add sorting.
+ 'sort' => array(
+ 'type' => 'field',
+ 'field' => 'field_text:value',
+ 'direction' => 'DESC',
+ ),
+ ),
+ ),
+ );
+
+ // Build a set of test data.
+ $node_values = array(
+ 'published1' => array(
+ 'type' => 'article',
+ 'status' => 1,
+ 'title' => 'Node published1 (<&>)',
+ 'uid' => 1,
+ 'field_text' => array(
+ LANGUAGE_NOT_SPECIFIED => array(
+ array(
+ 'value' => 1,
+ ),
+ ),
+ ),
+ ),
+ 'published2' => array(
+ 'type' => 'article',
+ 'status' => 1,
+ 'title' => 'Node published2 (<&>)',
+ 'uid' => 1,
+ 'field_text' => array(
+ LANGUAGE_NOT_SPECIFIED => array(
+ array(
+ 'value' => 2,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ $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;
+
+ $handler = entity_reference_get_selection_handler($field, $instance);
+
+ // Not only assert the result, but make sure the keys are sorted as
+ // expected.
+ $result = $handler->getReferencableEntities();
+ $expected_result = array(
+ $nodes['published2']->nid => $node_labels['published2'],
+ $nodes['published1']->nid => $node_labels['published1'],
+ );
+ $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.');
+
+ // Assert sort by property.
+ $instance['sort'] = array(
+ 'type' => 'property',
+ 'field' => 'nid',
+ 'direction' => 'DESC',
+ );
+ $handler = entity_reference_get_selection_handler($field, $instance);
+
+ $result = $handler->getReferencableEntities();
+ $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.');
+ }
+}
diff --git a/core/modules/field/modules/options/options.module b/core/modules/field/modules/options/options.module
index e958510..e31e70b 100644
--- a/core/modules/field/modules/options/options.module
+++ b/core/modules/field/modules/options/options.module
@@ -444,14 +444,14 @@ function options_field_widget_info() {
return array(
'options_select' => array(
'label' => t('Select list'),
- 'field types' => array('list_integer', 'list_float', 'list_text'),
+ 'field types' => array('list_integer', 'list_float', 'list_text', 'entity_reference'),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
),
),
'options_buttons' => array(
'label' => t('Check boxes/radio buttons'),
- 'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
+ 'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean', 'entity_reference'),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
),
diff --git a/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/Views.php b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/Views.php
new file mode 100644
index 0000000..2f0329d
--- /dev/null
+++ b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/Views.php
@@ -0,0 +1,220 @@
+field = $field;
+ $this->instance = $instance;
+ $this->entity = $entity;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::settingsForm().
+ */
+ public static function settingsForm($field, $instance) {
+ $view_settings = empty($instance['settings']['handler_settings']['view']) ? '' : $instance['settings']['handler_settings']['view'];
+ $displays = views_get_applicable_views('entity_reference_display');
+ // Filter views that list the entity type we want, and group the separate
+ // displays by view.
+ $entity_info = entity_get_info($field['settings']['target_type']);
+ $options = array();
+ foreach ($displays as $data) {
+ list($view, $display_id) = $data;
+ if ($view->storage->base_table == $entity_info['base table']) {
+ $options[$view->storage->name . ':' . $display_id] = $view->storage->name . ' - ' . $view->storage->display[$display_id]['display_title'];
+ }
+ }
+
+ // The value of the 'view_and_display' select below will need to be split
+ // into 'view_name' and 'view_display' in the final submitted values, so
+ // we massage the data at validate time on the wrapping element (not
+ // ideal).
+ $plugin = new static($field, $instance);
+ $form['view']['#element_validate'] = array(array($plugin, 'settingsFormValidate'));
+
+ if ($options) {
+ $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
+ $form['view']['view_and_display'] = array(
+ '#type' => 'select',
+ '#title' => t('View used to select the entities'),
+ '#required' => TRUE,
+ '#options' => $options,
+ '#default_value' => $default,
+ '#description' => '' . t('Choose the view and display that select the entities that can be referenced.
Only views with a display of type "Entity Reference" are eligible.') . '
',
+ );
+
+ $default = !empty($view_settings['args']) ? implode(', ', $view_settings['args']) : '';
+ $form['view']['args'] = array(
+ '#type' => 'textfield',
+ '#title' => t('View arguments'),
+ '#default_value' => $default,
+ '#required' => FALSE,
+ '#description' => t('Provide a comma separated list of arguments to pass to the view.'),
+ );
+ }
+ else {
+ $form['view']['no_view_help'] = array(
+ '#markup' => '' . t('No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view.', array(
+ '@create' => url('admin/structure/views/add'),
+ '@existing' => url('admin/structure/views'),
+ )) . '
',
+ );
+ }
+ return $form;
+ }
+
+ /**
+ * Initializes a view.
+ *
+ * @param string $match
+ * @param string $match_operator
+ * @param int $limit
+ * @param array $ids
+ *
+ * @return bool
+ * Return TRUE if the views was initialized, FALSE otherwise.
+ */
+ protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
+ $view_name = $this->instance['settings']['handler_settings']['view']['view_name'];
+ $display_name = $this->instance['settings']['handler_settings']['view']['display_name'];
+ $args = $this->instance['settings']['handler_settings']['view']['args'];
+ $entity_type = $this->field['settings']['target_type'];
+
+ // Check that the view is valid and the display still exists.
+ $this->view = views_get_view($view_name);
+ if (!$this->view || !$this->view->storage->getDisplay($display_name) || !$this->view->access($display_name)) {
+ watchdog('entity_reference', 'The view %view_name is no longer eligible for the %field_name field.', array('%view_name' => $view_name, '%field_name' => $this->instance['label']), WATCHDOG_WARNING);
+ return FALSE;
+ }
+ $this->view->setDisplay($display_name);
+
+ // Pass options to the display handler to make them available later.
+ $entity_reference_options = array(
+ 'match' => $match,
+ 'match_operator' => $match_operator,
+ 'limit' => $limit,
+ 'ids' => $ids,
+ );
+ $this->view->displayHandlers[$display_name]->setOption('entity_reference_options', $entity_reference_options);
+ return TRUE;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::getReferencableEntities().
+ */
+ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+ $display_name = $this->instance['settings']['handler_settings']['view']['display_name'];
+ $args = $this->instance['settings']['handler_settings']['view']['args'];
+ $result = array();
+ if ($this->initializeView($match, $match_operator, $limit)) {
+ // Get the results.
+ $result = $this->view->executeDisplay($display_name, $args);
+ }
+
+ $return = array();
+ if ($result) {
+ $target_type = $this->field['settings']['target_type'];
+ $entities = entity_load_multiple($target_type, array_keys($result));
+ foreach($entities as $entity) {
+ $return[$entity->bundle()][$entity->id()] = $result[$entity->id()];
+ }
+ }
+ return $return;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::countReferencableEntities().
+ */
+ public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
+ $this->getReferencableEntities($match, $match_operator);
+ return $this->view->total_items;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::validateReferencableEntities().
+ */
+ public function validateReferencableEntities(array $ids) {
+ $display_name = $this->instance['settings']['handler_settings']['view']['display_name'];
+ $args = $this->instance['settings']['handler_settings']['view']['args'];
+ $result = array();
+ if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
+ // Get the results.
+ $entities = $this->view->executeDisplay($display_name, $args);
+ $result = array_keys($entities);
+ }
+ return $result;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::validateAutocompleteInput().
+ */
+ public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
+ return NULL;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::entityFieldQueryAlter().
+ */
+ public function entityFieldQueryAlter(SelectInterface $query) { }
+
+ /**
+ * Element validate; Check View is valid.
+ */
+ public function settingsFormValidate($element, &$form_state, $form) {
+ // Split view name and display name from the 'view_and_display' value.
+ if (!empty($element['view_and_display']['#value'])) {
+ list($view, $display) = explode(':', $element['view_and_display']['#value']);
+ }
+ else {
+ form_error($element, t('The views entity selection mode requires a view.'));
+ return;
+ }
+
+ // Explode the 'args' string into an actual array. Beware, explode() turns an
+ // empty string into an array with one empty string. We'll need an empty array
+ // instead.
+ $args_string = trim($element['args']['#value']);
+ if ($args_string === '') {
+ $args = array();
+ }
+ else {
+ // array_map is called to trim whitespaces from the arguments.
+ $args = array_map('trim', explode(',', $args_string));
+ }
+
+ $value = array('view_name' => $view, 'display_name' => $display, 'args' => $args);
+ form_set_value($element, $value, $form_state);
+ }
+}