diff --git a/core/MAINTAINERS.txt b/core/MAINTAINERS.txt
index 8f8edb2..5699b09 100644
--- a/core/MAINTAINERS.txt
+++ b/core/MAINTAINERS.txt
@@ -207,6 +207,10 @@ Database Logging module
Edit module
- Wim Leers 'Wim Leers' http://drupal.org/user/99777
+Entity Reference module
+- Amitai Burstein 'Amitaibu' http://drupal.org/user/57511
+- Andrei Mateescu 'amateescu' http://drupal.org/user/729614
+
Field module
- Yves Chedemois 'yched' http://drupal.org/user/39567
- Barry Jaspan 'bjaspan' http://drupal.org/user/46413
diff --git a/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php b/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php
index 6c4a6fc..1b9f53e 100644
--- a/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php
+++ b/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php
@@ -2,19 +2,18 @@
/**
* @file
- * Definition of Drupal\Core\Entity\Field\Type\EntityReferenceItem.
+ * Contains Drupal\Core\Entity\Field\Type\EntityReferenceItem.
*/
namespace Drupal\Core\Entity\Field\Type;
-use Drupal\Core\Entity\Field\FieldItemBase;
-use InvalidArgumentException;
+use \Drupal\Core\Entity\Field\FieldItemBase;
/**
- * Defines the 'entityreference_field' entity field item.
+ * Defines the 'entity_reference' entity field item.
*
- * Available settings (below the definition's 'settings' key) are:
- * - entity type: (required) The entity type to reference.
+ * Required settings (below the definition's 'settings' key) are:
+ * - target_type: The entity type to reference.
*/
class EntityReferenceItem extends FieldItemBase {
@@ -28,36 +27,36 @@ class EntityReferenceItem extends FieldItemBase {
static $propertyDefinitions;
/**
- * Implements ComplexDataInterface::getPropertyDefinitions().
+ * Implements \Drupal\Core\TypedData\ComplexDataInterface::getPropertyDefinitions().
*/
public function getPropertyDefinitions() {
// Definitions vary by entity type, so key them by entity type.
- $entity_type = $this->definition['settings']['entity type'];
+ $target_type = $this->definition['settings']['target_type'];
- if (!isset(self::$propertyDefinitions[$entity_type])) {
- self::$propertyDefinitions[$entity_type]['value'] = array(
+ if (!isset(self::$propertyDefinitions[$target_type])) {
+ self::$propertyDefinitions[$target_type]['target_id'] = array(
// @todo: Lookup the entity type's ID data type and use it here.
'type' => 'integer',
'label' => t('Entity ID'),
);
- self::$propertyDefinitions[$entity_type]['entity'] = array(
+ self::$propertyDefinitions[$target_type]['entity'] = array(
'type' => 'entity',
'constraints' => array(
- 'entity type' => $entity_type,
+ 'entity type' => $target_type,
),
'label' => t('Entity'),
'description' => t('The referenced entity'),
- // The entity object is computed out of the entity id.
+ // The entity object is computed out of the entity ID.
'computed' => TRUE,
'read-only' => FALSE,
- 'settings' => array('id source' => 'value'),
+ 'settings' => array('id source' => 'target_id'),
);
}
- return self::$propertyDefinitions[$entity_type];
+ return self::$propertyDefinitions[$target_type];
}
/**
- * Overrides FieldItemBase::setValue().
+ * Overrides \Drupal\Core\Entity\Field\FieldItemBase::setValue().
*/
public function setValue($values) {
// Treat the values as property value of the entity field, if no array
@@ -68,8 +67,8 @@ public function setValue($values) {
// Entity is computed out of the ID, so we only need to update the ID. Only
// set the entity field if no ID is given.
- if (isset($values['value'])) {
- $this->properties['value']->setValue($values['value']);
+ if (isset($values['target_id'])) {
+ $this->properties['target_id']->setValue($values['target_id']);
}
elseif (isset($values['entity'])) {
$this->properties['entity']->setValue($values['entity']);
@@ -77,9 +76,17 @@ public function setValue($values) {
else {
$this->properties['entity']->setValue(NULL);
}
- unset($values['entity'], $values['value']);
+ unset($values['entity'], $values['target_id']);
if ($values) {
- throw new InvalidArgumentException('Property ' . key($values) . ' is unknown.');
+ throw new \InvalidArgumentException('Property ' . key($values) . ' is unknown.');
}
}
+
+ /**
+ * Overrides \Drupal\Core\Entity\Field\FieldItemBase::get().
+ */
+ public function get($property_name) {
+ $property_name = ($property_name == 'value') ? 'target_id' : $property_name;
+ return parent::get($property_name);
+ }
}
diff --git a/core/modules/comment/comment.admin.inc b/core/modules/comment/comment.admin.inc
index b9d34a6..0418b1d 100644
--- a/core/modules/comment/comment.admin.inc
+++ b/core/modules/comment/comment.admin.inc
@@ -124,7 +124,7 @@ function comment_admin_overview($form, &$form_state, $arg) {
'data' => array(
'#type' => 'link',
'#title' => $node_title,
- '#href' => 'node/' . $comment->nid->value,
+ '#href' => 'node/' . $comment->nid->target_id,
),
),
'changed' => format_date($comment->changed->value, 'short'),
@@ -293,7 +293,7 @@ function comment_confirm_delete($form, &$form_state, Comment $comment) {
return confirm_form(
$form,
t('Are you sure you want to delete the comment %title?', array('%title' => $comment->subject->value)),
- 'node/' . $comment->nid->value,
+ 'node/' . $comment->nid->target_id,
t('Any replies to this comment will be lost. This action cannot be undone.'),
t('Delete'),
t('Cancel'),
@@ -312,5 +312,5 @@ function comment_confirm_delete_submit($form, &$form_state) {
// Clear the cache so an anonymous user sees that his comment was deleted.
cache_invalidate_tags(array('content' => TRUE));
- $form_state['redirect'] = "node/{$comment->nid->value}";
+ $form_state['redirect'] = "node/{$comment->nid->target_id}";
}
diff --git a/core/modules/comment/comment.api.php b/core/modules/comment/comment.api.php
index cb4133d..793d9ad 100644
--- a/core/modules/comment/comment.api.php
+++ b/core/modules/comment/comment.api.php
@@ -34,7 +34,7 @@ function hook_comment_presave(Drupal\comment\Comment $comment) {
*/
function hook_comment_insert(Drupal\comment\Comment $comment) {
// Reindex the node when comments are added.
- search_touch_node($comment->nid->value);
+ search_touch_node($comment->nid->target_id);
}
/**
@@ -45,7 +45,7 @@ function hook_comment_insert(Drupal\comment\Comment $comment) {
*/
function hook_comment_update(Drupal\comment\Comment $comment) {
// Reindex the node when comments are updated.
- search_touch_node($comment->nid->value);
+ search_touch_node($comment->nid->target_id);
}
/**
diff --git a/core/modules/comment/comment.module b/core/modules/comment/comment.module
index 3bcabfe..fb10649 100644
--- a/core/modules/comment/comment.module
+++ b/core/modules/comment/comment.module
@@ -933,7 +933,7 @@ function comment_links(Comment $comment, Node $node) {
);
$links['comment-reply'] = array(
'title' => t('reply'),
- 'href' => "comment/reply/{$comment->nid->value}/{$comment->id()}",
+ 'href' => "comment/reply/{$comment->nid->target_id}/{$comment->id()}",
'html' => TRUE,
);
if ($comment->status->value == COMMENT_NOT_PUBLISHED) {
@@ -955,7 +955,7 @@ function comment_links(Comment $comment, Node $node) {
}
$links['comment-reply'] = array(
'title' => t('reply'),
- 'href' => "comment/reply/{$comment->nid->value}/{$comment->id()}",
+ 'href' => "comment/reply/{$comment->nid->target_id}/{$comment->id()}",
'html' => TRUE,
);
}
@@ -1310,7 +1310,7 @@ function comment_user_cancel($edit, $account, $method) {
case 'user_cancel_reassign':
$comments = entity_load_multiple_by_properties('comment', array('uid' => $account->uid));
foreach ($comments as $comment) {
- $comment->uid->value = 0;
+ $comment->uid->target_id = 0;
comment_save($comment);
}
break;
@@ -1345,7 +1345,7 @@ function comment_access($op, Comment $comment) {
global $user;
if ($op == 'edit') {
- return ($user->uid && $user->uid == $comment->uid->value && $comment->status->value == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
+ return ($user->uid && $user->uid == $comment->uid->target_id && $comment->status->value == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
}
}
@@ -1548,7 +1548,7 @@ function comment_preview(Comment $comment) {
}
if (!empty($account->uid)) {
- $comment->uid->value = $account->uid;
+ $comment->uid->target_id = $account->uid;
$comment->name->value = check_plain($account->name);
}
elseif (empty($comment->name->value)) {
@@ -1564,7 +1564,7 @@ function comment_preview(Comment $comment) {
$preview_build['comment_preview'] = $comment_build;
}
- if ($comment->pid->value) {
+ if ($comment->pid->target_id) {
$build = array();
$comment = $comment->pid->entity;
if ($comment && $comment->status->value == COMMENT_PUBLISHED) {
@@ -1653,7 +1653,7 @@ function template_preprocess_comment(&$variables) {
$variables['permalink'] = l(t('Permalink'), $uri['path'], $uri['options']);
$variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['author'], '!datetime' => $variables['created']));
- if ($comment->pid->value) {
+ if ($comment->pid->target_id) {
// Fetch and store the parent comment information for use in templates.
$comment_parent = $comment->pid->entity;
$account_parent = comment_prepare_author($comment);
@@ -1708,14 +1708,14 @@ function template_preprocess_comment(&$variables) {
if ($variables['new']) {
$variables['attributes']['class'][] = 'new';
}
- if (!$comment->uid->value) {
+ if (!$comment->uid->target_id) {
$variables['attributes']['class'][] = 'by-anonymous';
}
else {
- if ($comment->uid->value == $variables['node']->uid) {
+ if ($comment->uid->target_id == $variables['node']->uid) {
$variables['attributes']['class'][] = 'by-node-author';
}
- if ($comment->uid->value == $variables['user']->uid) {
+ if ($comment->uid->target_id == $variables['user']->uid) {
$variables['attributes']['class'][] = 'by-viewer';
}
}
diff --git a/core/modules/comment/comment.pages.inc b/core/modules/comment/comment.pages.inc
index e333dd7..da359a4 100644
--- a/core/modules/comment/comment.pages.inc
+++ b/core/modules/comment/comment.pages.inc
@@ -59,7 +59,7 @@ function comment_reply(Node $node, $pid = NULL) {
if ($comment->status->value == COMMENT_PUBLISHED) {
// If that comment exists, make sure that the current comment and the
// parent comment both belong to the same parent node.
- if ($comment->nid->value != $node->nid) {
+ if ($comment->nid->target_id != $node->nid) {
// Attempting to reply to a comment not belonging to the current nid.
drupal_set_message(t('The comment you are replying to does not exist.'), 'error');
drupal_goto("node/$node->nid");
@@ -121,7 +121,7 @@ function comment_approve($cid) {
comment_save($comment);
drupal_set_message(t('Comment approved.'));
- drupal_goto('node/' . $comment->nid->value);
+ drupal_goto('node/' . $comment->nid->target_id);
}
throw new NotFoundHttpException();
}
diff --git a/core/modules/comment/comment.tokens.inc b/core/modules/comment/comment.tokens.inc
index ec56287..715b63d 100644
--- a/core/modules/comment/comment.tokens.inc
+++ b/core/modules/comment/comment.tokens.inc
@@ -131,13 +131,13 @@ function comment_tokens($type, $tokens, array $data = array(), array $options =
break;
case 'name':
- $name = ($comment->uid->value == 0) ? config('user.settings')->get('anonymous') : $comment->name->value;
+ $name = ($comment->uid->target_id == 0) ? config('user.settings')->get('anonymous') : $comment->name->value;
$replacements[$original] = $sanitize ? filter_xss($name) : $name;
break;
case 'mail':
- if ($comment->uid->value != 0) {
- $account = user_load($comment->uid->value);
+ if ($comment->uid->target_id != 0) {
+ $account = user_load($comment->uid->target_id);
$mail = $account->mail;
}
else {
@@ -175,8 +175,8 @@ function comment_tokens($type, $tokens, array $data = array(), array $options =
break;
case 'parent':
- if (!empty($comment->pid->value)) {
- $parent = comment_load($comment->pid->value);
+ if (!empty($comment->pid->target_id)) {
+ $parent = comment_load($comment->pid->target_id);
$replacements[$original] = $sanitize ? filter_xss($parent->subject) : $parent->subject;
}
break;
diff --git a/core/modules/comment/lib/Drupal/comment/CommentFormController.php b/core/modules/comment/lib/Drupal/comment/CommentFormController.php
index fca09ba..c13711f 100644
--- a/core/modules/comment/lib/Drupal/comment/CommentFormController.php
+++ b/core/modules/comment/lib/Drupal/comment/CommentFormController.php
@@ -37,8 +37,8 @@ public function form(array $form, array &$form_state, EntityInterface $comment)
// If not replying to a comment, use our dedicated page callback for new
// comments on nodes.
- if (!$comment->id() && !$comment->pid->value) {
- $form['#action'] = url('comment/reply/' . $comment->nid->value);
+ if (!$comment->id() && !$comment->pid->target_id) {
+ $form['#action'] = url('comment/reply/' . $comment->nid->target_id);
}
if (isset($form_state['comment_preview'])) {
@@ -163,7 +163,7 @@ public function form(array $form, array &$form_state, EntityInterface $comment)
// Used for conditional validation of author fields.
$form['is_anonymous'] = array(
'#type' => 'value',
- '#value' => ($comment->id() ? !$comment->uid->value : !$user->uid),
+ '#value' => ($comment->id() ? !$comment->uid->target_id : !$user->uid),
);
// Make the comment inherit the current content language unless specifically
@@ -175,7 +175,8 @@ public function form(array $form, array &$form_state, EntityInterface $comment)
// Add internal comment properties.
foreach (array('cid', 'pid', 'nid', 'uid', 'node_type', 'langcode') as $key) {
- $form[$key] = array('#type' => 'value', '#value' => $comment->$key->value);
+ $key_name = key($comment->$key->offsetGet(0)->getProperties());
+ $form[$key] = array('#type' => 'value', '#value' => $comment->$key->{$key_name});
}
return parent::form($form, $form_state, $comment);
@@ -275,7 +276,7 @@ public function submit(array $form, array &$form_state) {
// @todo Too fragile. Should be prepared and stored in comment_form()
// already.
if (!$comment->is_anonymous && !empty($comment->name->value) && ($account = user_load_by_name($comment->name->value))) {
- $comment->uid->value = $account->uid;
+ $comment->uid->target_id = $account->uid;
}
// If the comment was posted by an anonymous user and no author name was
// required, use "Anonymous" by default.
diff --git a/core/modules/comment/lib/Drupal/comment/CommentRenderController.php b/core/modules/comment/lib/Drupal/comment/CommentRenderController.php
index a5ace07..dab8dc4 100644
--- a/core/modules/comment/lib/Drupal/comment/CommentRenderController.php
+++ b/core/modules/comment/lib/Drupal/comment/CommentRenderController.php
@@ -31,7 +31,7 @@ public function buildContent(array $entities, array $displays, $view_mode, $lang
// Pre-load associated users into cache to leverage multiple loading.
$uids = array();
foreach ($entities as $entity) {
- $uids[] = $entity->uid->value;
+ $uids[] = $entity->uid->target_id;
}
user_load_multiple(array_unique($uids));
@@ -40,13 +40,13 @@ public function buildContent(array $entities, array $displays, $view_mode, $lang
// Load all nodes of all comments at once.
$nids = array();
foreach ($entities as $entity) {
- $nids[$entity->nid->value] = $entity->nid->value;
+ $nids[$entity->nid->target_id] = $entity->nid->target_id;
}
$nodes = node_load_multiple($nids);
foreach ($entities as $entity) {
- if (isset($nodes[$entity->nid->value])) {
- $node = $nodes[$entity->nid->value];
+ if (isset($nodes[$entity->nid->target_id])) {
+ $node = $nodes[$entity->nid->target_id];
}
else {
throw new \InvalidArgumentException(t('Invalid node for comment.'));
diff --git a/core/modules/comment/lib/Drupal/comment/CommentStorageController.php b/core/modules/comment/lib/Drupal/comment/CommentStorageController.php
index 4c91741..78a4ca4 100644
--- a/core/modules/comment/lib/Drupal/comment/CommentStorageController.php
+++ b/core/modules/comment/lib/Drupal/comment/CommentStorageController.php
@@ -104,10 +104,10 @@ protected function preSave(EntityInterface $comment) {
// is extended in a faulty manner.
throw new LogicException('preSave is called again without calling postSave() or releaseThreadLock()');
}
- if ($comment->pid->value == 0) {
+ if ($comment->pid->target_id == 0) {
// This is a comment with no parent comment (depth 0): we start
// by retrieving the maximum thread level.
- $max = db_query('SELECT MAX(thread) FROM {comment} WHERE nid = :nid', array(':nid' => $comment->nid->value))->fetchField();
+ $max = db_query('SELECT MAX(thread) FROM {comment} WHERE nid = :nid', array(':nid' => $comment->nid->target_id))->fetchField();
// Strip the "/" from the end of the thread.
$max = rtrim($max, '/');
// We need to get the value at the correct depth.
@@ -127,7 +127,7 @@ protected function preSave(EntityInterface $comment) {
// Get the max value in *this* thread.
$max = db_query("SELECT MAX(thread) FROM {comment} WHERE thread LIKE :thread AND nid = :nid", array(
':thread' => $parent->thread->value . '.%',
- ':nid' => $comment->nid->value,
+ ':nid' => $comment->nid->target_id,
))->fetchField();
if ($max == '') {
@@ -150,7 +150,7 @@ protected function preSave(EntityInterface $comment) {
// has the lock, just move to the next integer.
do {
$thread = $prefix . comment_int_to_alphadecimal(++$n) . '/';
- } while (!lock()->acquire("comment:{$comment->nid->value}:$thread"));
+ } while (!lock()->acquire("comment:{$comment->nid->target_id}:$thread"));
$this->threadLock = $thread;
}
if (empty($comment->created->value)) {
@@ -161,7 +161,7 @@ protected function preSave(EntityInterface $comment) {
}
// We test the value with '===' because we need to modify anonymous
// users as well.
- if ($comment->uid->value === $user->uid && isset($user->name)) {
+ if ($comment->uid->target_id === $user->uid && isset($user->name)) {
$comment->name->value = $user->name;
}
// Add the values which aren't passed into the function.
@@ -176,7 +176,7 @@ protected function preSave(EntityInterface $comment) {
protected function postSave(EntityInterface $comment, $update) {
$this->releaseThreadLock();
// Update the {node_comment_statistics} table prior to executing the hook.
- $this->updateNodeStatistics($comment->nid->value);
+ $this->updateNodeStatistics($comment->nid->target_id);
if ($comment->status->value == COMMENT_PUBLISHED) {
module_invoke_all('comment_publish', $comment);
}
@@ -194,7 +194,7 @@ protected function postDelete($comments) {
comment_delete_multiple($child_cids);
foreach ($comments as $comment) {
- $this->updateNodeStatistics($comment->nid->value);
+ $this->updateNodeStatistics($comment->nid->target_id);
}
}
@@ -287,14 +287,14 @@ public function baseFieldDefinitions() {
$properties['pid'] = array(
'label' => t('Parent ID'),
'description' => t('The parent comment ID if this is a reply to a comment.'),
- 'type' => 'entityreference_field',
- 'settings' => array('entity type' => 'comment'),
+ 'type' => 'entity_reference_field',
+ 'settings' => array('target_type' => 'comment'),
);
$properties['nid'] = array(
'label' => t('Node ID'),
'description' => t('The ID of the node of which this comment is a reply.'),
- 'type' => 'entityreference_field',
- 'settings' => array('entity type' => 'node'),
+ 'type' => 'entity_reference_field',
+ 'settings' => array('target_type' => 'node'),
'required' => TRUE,
);
$properties['langcode'] = array(
@@ -310,8 +310,8 @@ public function baseFieldDefinitions() {
$properties['uid'] = array(
'label' => t('User ID'),
'description' => t('The user ID of the comment author.'),
- 'type' => 'entityreference_field',
- 'settings' => array('entity type' => 'user'),
+ 'type' => 'entity_reference_field',
+ 'settings' => array('target_type' => 'user'),
);
$properties['name'] = array(
'label' => t('Name'),
diff --git a/core/modules/comment/lib/Drupal/comment/FieldNewValue.php b/core/modules/comment/lib/Drupal/comment/FieldNewValue.php
index c3e0d94..52875ca 100644
--- a/core/modules/comment/lib/Drupal/comment/FieldNewValue.php
+++ b/core/modules/comment/lib/Drupal/comment/FieldNewValue.php
@@ -28,7 +28,7 @@ public function getValue($langcode = NULL) {
}
$field = $this->parent->getParent();
$entity = $field->getParent();
- $this->value = node_mark($entity->nid->value, $entity->changed->value);
+ $this->value = node_mark($entity->nid->target_id, $entity->changed->value);
}
return $this->value;
}
diff --git a/core/modules/comment/lib/Drupal/comment/Plugin/Core/Entity/Comment.php b/core/modules/comment/lib/Drupal/comment/Plugin/Core/Entity/Comment.php
index c6175af..23f22d0 100644
--- a/core/modules/comment/lib/Drupal/comment/Plugin/Core/Entity/Comment.php
+++ b/core/modules/comment/lib/Drupal/comment/Plugin/Core/Entity/Comment.php
@@ -186,7 +186,7 @@ class Comment extends EntityNG implements ContentEntityInterface {
protected $values = array(
'langcode' => array(LANGUAGE_DEFAULT => array(0 => array('value' => LANGUAGE_NOT_SPECIFIED))),
'name' => array(LANGUAGE_DEFAULT => array(0 => array('value' => ''))),
- 'uid' => array(LANGUAGE_DEFAULT => array(0 => array('value' => 0))),
+ 'uid' => array(LANGUAGE_DEFAULT => array(0 => array('target_id' => 0))),
);
/**
diff --git a/core/modules/comment/lib/Drupal/comment/Plugin/entity_reference/selection/CommentSelection.php b/core/modules/comment/lib/Drupal/comment/Plugin/entity_reference/selection/CommentSelection.php
new file mode 100644
index 0000000..8010f19
--- /dev/null
+++ b/core/modules/comment/lib/Drupal/comment/Plugin/entity_reference/selection/CommentSelection.php
@@ -0,0 +1,81 @@
+condition('status', COMMENT_PUBLISHED);
+ }
+ return $query;
+ }
+
+ /**
+ * Overrides SelectionBase::entityQueryAlter().
+ */
+ public function entityQueryAlter(SelectInterface $query) {
+ $tables = $query->getTables();
+ $base_table = $tables['base_table']['alias'];
+
+ // 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::entityQueryAlter()
+ if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
+ $query->condition($node_alias . '.status', 1);
+ }
+ }
+}
diff --git a/core/modules/comment/lib/Drupal/comment/Tests/CommentInterfaceTest.php b/core/modules/comment/lib/Drupal/comment/Tests/CommentInterfaceTest.php
index 36f9f43..24a7931 100644
--- a/core/modules/comment/lib/Drupal/comment/Tests/CommentInterfaceTest.php
+++ b/core/modules/comment/lib/Drupal/comment/Tests/CommentInterfaceTest.php
@@ -67,7 +67,7 @@ function testCommentInterface() {
// Test changing the comment author to "Anonymous".
$this->drupalGet('comment/' . $comment->id() . '/edit');
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->subject->value, array('name' => ''));
- $this->assertTrue(empty($comment->name->value) && $comment->uid->value == 0, 'Comment author successfully changed to anonymous.');
+ $this->assertTrue(empty($comment->name->value) && $comment->uid->target_id == 0, 'Comment author successfully changed to anonymous.');
// Test changing the comment author to an unverified user.
$random_name = $this->randomName();
@@ -79,7 +79,7 @@ function testCommentInterface() {
// Test changing the comment author to a verified user.
$this->drupalGet('comment/' . $comment->id() . '/edit');
$comment = $this->postComment(NULL, $comment->comment_body->value, $comment->subject->value, array('name' => $this->web_user->name));
- $this->assertTrue($comment->name->value == $this->web_user->name && $comment->uid->value == $this->web_user->uid, 'Comment author successfully changed to a registered user.');
+ $this->assertTrue($comment->name->value == $this->web_user->name && $comment->uid->target_id == $this->web_user->uid, 'Comment author successfully changed to a registered user.');
$this->drupalLogout();
@@ -92,7 +92,7 @@ function testCommentInterface() {
$reply = $this->postComment(NULL, $this->randomName(), '', TRUE);
$reply_loaded = comment_load($reply->id());
$this->assertTrue($this->commentExists($reply, TRUE), 'Reply found.');
- $this->assertEqual($comment->id(), $reply_loaded->pid->value, 'Pid of a reply to a comment is set correctly.');
+ $this->assertEqual($comment->id(), $reply_loaded->pid->target_id, 'Pid of a reply to a comment is set correctly.');
$this->assertEqual(rtrim($comment->thread->value, '/') . '.00/', $reply_loaded->thread->value, 'Thread of reply grows correctly.');
// Second reply to comment #3 creating comment #4.
diff --git a/core/modules/comment/lib/Drupal/comment/Tests/CommentTokenReplaceTest.php b/core/modules/comment/lib/Drupal/comment/Tests/CommentTokenReplaceTest.php
index 5421c0b..6bcc992 100644
--- a/core/modules/comment/lib/Drupal/comment/Tests/CommentTokenReplaceTest.php
+++ b/core/modules/comment/lib/Drupal/comment/Tests/CommentTokenReplaceTest.php
@@ -61,11 +61,11 @@ function testCommentTokenReplacement() {
$tests['[comment:edit-url]'] = url('comment/' . $comment->id() . '/edit', $url_options);
$tests['[comment:created:since]'] = format_interval(REQUEST_TIME - $comment->created->value, 2, $language_interface->langcode);
$tests['[comment:changed:since]'] = format_interval(REQUEST_TIME - $comment->changed->value, 2, $language_interface->langcode);
- $tests['[comment:parent:cid]'] = $comment->pid->value;
+ $tests['[comment:parent:cid]'] = $comment->pid->target_id;
$tests['[comment:parent:title]'] = check_plain($parent_comment->subject->value);
- $tests['[comment:node:nid]'] = $comment->nid->value;
+ $tests['[comment:node:nid]'] = $comment->nid->target_id;
$tests['[comment:node:title]'] = check_plain($node->title);
- $tests['[comment:author:uid]'] = $comment->uid->value;
+ $tests['[comment:author:uid]'] = $comment->uid->target_id;
$tests['[comment:author:name]'] = check_plain($this->admin_user->name);
// Test to make sure that we generated something for each token.
diff --git a/core/modules/comment/lib/Drupal/comment/Tests/Views/DefaultViewRecentComments.php b/core/modules/comment/lib/Drupal/comment/Tests/Views/DefaultViewRecentComments.php
index fa0145d..3006f94 100644
--- a/core/modules/comment/lib/Drupal/comment/Tests/Views/DefaultViewRecentComments.php
+++ b/core/modules/comment/lib/Drupal/comment/Tests/Views/DefaultViewRecentComments.php
@@ -78,8 +78,8 @@ public function setUp() {
// Create some comments and attach them to the created node.
for ($i = 0; $i < $this->masterDisplayResults; $i++) {
$comment = entity_create('comment', array('node_type' => 'comment_node_' . $this->node->type));
- $comment->uid->value = 0;
- $comment->nid->value = $this->node->nid;
+ $comment->uid->target_id = 0;
+ $comment->nid->target_id = $this->node->nid;
$comment->subject->value = 'Test comment ' . $i;
$comment->comment_body->value = 'Test body ' . $i;
$comment->comment_body->format = 'full_html';
@@ -107,7 +107,7 @@ public function testBlockDisplay() {
);
$expected_result = array();
foreach (array_values($this->commentsCreated) as $key => $comment) {
- $expected_result[$key]['nid'] = $comment->nid->value;
+ $expected_result[$key]['nid'] = $comment->nid->target_id;
$expected_result[$key]['subject'] = $comment->subject->value;
$expected_result[$key]['cid'] = $comment->id();
$expected_result[$key]['changed'] = $comment->changed->value;
@@ -139,7 +139,7 @@ public function testPageDisplay() {
);
$expected_result = array();
foreach (array_values($this->commentsCreated) as $key => $comment) {
- $expected_result[$key]['nid'] = $comment->nid->value;
+ $expected_result[$key]['nid'] = $comment->nid->target_id;
$expected_result[$key]['subject'] = $comment->subject->value;
$expected_result[$key]['changed'] = $comment->changed->value;
$expected_result[$key]['created'] = $comment->created->value;
diff --git a/core/modules/entity_reference/css/entity_reference-rtl.admin.css b/core/modules/entity_reference/css/entity_reference-rtl.admin.css
new file mode 100644
index 0000000..3302ab8
--- /dev/null
+++ b/core/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/entity_reference/css/entity_reference.admin.css b/core/modules/entity_reference/css/entity_reference.admin.css
new file mode 100644
index 0000000..d608ccf
--- /dev/null
+++ b/core/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/entity_reference/entity_reference.info b/core/modules/entity_reference/entity_reference.info
new file mode 100644
index 0000000..2216092
--- /dev/null
+++ b/core/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/entity_reference/entity_reference.install b/core/modules/entity_reference/entity_reference.install
new file mode 100644
index 0000000..17030ef
--- /dev/null
+++ b/core/modules/entity_reference/entity_reference.install
@@ -0,0 +1,49 @@
+ 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.
+ // see http://drupal.org/node/1847582
+ // $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/entity_reference/entity_reference.module b/core/modules/entity_reference/entity_reference.module
new file mode 100644
index 0000000..6cf9afa
--- /dev/null
+++ b/core/modules/entity_reference/entity_reference.module
@@ -0,0 +1,543 @@
+ t('Entity Reference'),
+ 'description' => t('This field references 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' => 'base',
+ // The handler settings.
+ 'handler_settings' => array(),
+ ),
+ 'default_widget' => 'entity_reference_autocomplete',
+ 'default_formatter' => 'entity_reference_label',
+ 'field item class' => 'Drupal\Core\Entity\Field\Type\EntityReferenceItem',
+ );
+ return $field_info;
+}
+
+/**
+ * Implements hook_entity_field_info().
+ *
+ * Set the "target_type" property definition for entity reference fields.
+ *
+ * @see Drupal\Core\Entity\Field\Type\EntityReferenceItem::getPropertyDefinitions()
+ */
+function entity_reference_entity_field_info($entity_type) {
+ $property_info = array();
+ foreach (field_info_instances($entity_type) as $bundle_name => $instances) {
+ foreach ($instances as $field_name => $instance) {
+ $field = field_info_field($field_name);
+ if ($field['type'] != 'entity_reference') {
+ continue;
+ }
+ $property_info['definitions'][$field_name]['settings']['target_type'] = $field['settings']['target_type'];
+ }
+ }
+ return $property_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) {
+ if (!empty($item['target_id']) && $item['target_id'] == 'auto_create') {
+ // Allow auto-create entities.
+ return FALSE;
+ }
+ return !isset($item['target_id']) || !is_numeric($item['target_id']);
+}
+
+/**
+ * Implements hook_field_presave().
+ *
+ * Create an entity on the fly.
+ */
+function entity_reference_field_presave(EntityInterface $entity, $field, $instance, $langcode, &$items) {
+ global $user;
+ $target_type = $field['settings']['target_type'];
+ $entity_info = entity_get_info($target_type);
+
+ // Get the bundle.
+ if (!empty($instance['settings']['handler_settings']['target_bundles']) && count($instance['settings']['handler_settings']['target_bundles']) == 1) {
+ $bundle = reset($instance['settings']['handler_settings']['target_bundles']);
+ }
+ else {
+ $bundle = reset($entity_info['bundles']);
+ }
+
+ foreach ($items as $delta => $item) {
+ if ($item['target_id'] == 'auto_create') {
+ $bundle_key = $entity_info['entity_keys']['bundle'];
+ $label_key = $entity_info['entity_keys']['label'];
+ $values = array(
+ $label_key => $item['label'],
+ $bundle_key => $bundle,
+ // @todo: Use wrapper to get the user if exists or needed.
+ 'uid' => !empty($entity->uid) ? $entity->uid : $user->uid,
+ );
+ $target_entity = entity_create($target_type, $values);
+ $target_entity->save();
+ $items[$delta]['target_id'] = $target_entity->id();
+ }
+ }
+}
+
+
+/**
+ * Implements hook_field_validate().
+ */
+function entity_reference_field_validate(EntityInterface $entity = NULL, $field, $instance, $langcode, $items, &$errors) {
+ $ids = array();
+ foreach ($items as $delta => $item) {
+ if (!entity_reference_field_is_empty($item, $field) && $item['target_id'] !== 'auto_create') {
+ $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) does not exist.', 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) {
+ // @todo Remove this ugly hack, needed for now because Config entities have
+ // no EFQ support. Revisit after http://drupal.org/node/1853856 and
+ // http://drupal.org/node/1846454.
+ if (!is_subclass_of($entity_info['class'], '\Drupal\Core\Config\Entity\ConfigEntityBase')) {
+ $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' => 'base');
+
+ // 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. 'base', 'views', ..) and not entity
+ // type specific plugins (e.g. 'base_node', 'base_user', ...).
+ if (in_array($plugin_id, $handler_groups)) {
+ $handlers_options[$plugin_id] = check_plain($plugin['label']);
+ }
+ }
+
+ $form['handler'] = array(
+ '#type' => 'details',
+ '#title' => t('Reference type'),
+ '#tree' => TRUE,
+ '#process' => array('_entity_reference_form_process_merge_parent'),
+ );
+
+ $form['handler']['handler'] = array(
+ '#type' => 'select',
+ '#title' => t('Reference method'),
+ '#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 (!empty($element['#ajax'])) {
+ $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 'Selection' fieldset, we need to go one more level above
+ // because of our extra container.
+ if (isset($element['#title']) && $element['#title'] == t('Reference type')) {
+ 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->entityQueryAlter($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 ''.
+ *
+ * @return \Symfony\Component\HttpFoundation\JsonResponse
+ */
+function entity_reference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $entity_id = '') {
+ $field = field_info_field($field_name);
+ $instance = field_info_instance($entity_type, $field_name, $bundle_name);
+
+ // Get the typed string, if exists from the URL.
+ $tags_typed = drupal_container()->get('request')->query->get('q');
+ $tags_typed = drupal_explode_tags($tags_typed);
+ $string = drupal_strtolower(array_pop($tags_typed));
+
+ 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.
+ $match_operator = !empty($instance['widget']['settings']['match_operator']) ? $instance['widget']['settings']['match_operator'] : 'CONTAINS';
+ $entity_labels = $handler->getReferencableEntities($tag_last, $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/entity_reference/lib/Drupal/entity_reference/EntityReferenceBundle.php b/core/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceBundle.php
new file mode 100644
index 0000000..434937d
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceBundle.php
@@ -0,0 +1,26 @@
+register('plugin.manager.entity_reference.selection', 'Drupal\entity_reference\Plugin\Type\SelectionPluginManager');
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionBase.php
new file mode 100644
index 0000000..f8f784d
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionBase.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/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php
new file mode 100644
index 0000000..31c1cb1
--- /dev/null
+++ b/core/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, $strict = TRUE) { }
+
+ /**
+ * Implements SelectionInterface::entityQueryAlter().
+ */
+ public function entityQueryAlter(SelectInterface $query) { }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php
new file mode 100644
index 0000000..49ad461
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php
@@ -0,0 +1,81 @@
+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/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php
new file mode 100644
index 0000000..f89d340
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php
@@ -0,0 +1,332 @@
+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(
+ 'field' => '_none',
+ ),
+ 'auto_create' => FALSE,
+ );
+
+ if (!empty($entity_info['entity_keys']['bundle'])) {
+ $bundles = array();
+ foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
+ $bundles[$bundle_name] = $bundle_info['label'];
+ }
+
+ $target_bundles_title = t('Bundles');
+ // Default core entity types with sensible labels.
+ if ($field['settings']['target_type'] == 'node') {
+ $target_bundles_title = t('Content types');
+ }
+ elseif ($field['settings']['target_type'] == 'taxonomy_term') {
+ $target_bundles_title = t('Vocabularies');
+ }
+
+ $form['target_bundles'] = array(
+ '#type' => 'checkboxes',
+ '#title' => $target_bundles_title,
+ '#options' => $bundles,
+ '#default_value' => (!empty($instance['settings']['handler_settings']['target_bundles'])) ? $instance['settings']['handler_settings']['target_bundles'] : array_keys($bundles),
+ '#size' => 6,
+ '#multiple' => TRUE,
+ '#element_validate' => array('_entity_reference_element_validate_filter'),
+ );
+ }
+ else {
+ $form['target_bundles'] = array(
+ '#type' => 'value',
+ '#value' => array(),
+ );
+ }
+
+ // @todo Use Entity::getPropertyDefinitions() when all entity types are
+ // converted to the new Field API.
+ $fields = drupal_map_assoc($entity_info['schema_fields_sql']['base_table']);
+ foreach (field_info_instances($field['settings']['target_type']) as $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)', array('@label' => $instance_info['label'], '@column' => $column_name));
+ }
+ }
+ }
+
+ $form['sort']['field'] = array(
+ '#type' => 'select',
+ '#title' => t('Sort by'),
+ '#options' => array(
+ '_none' => t('- None -'),
+ ) + $fields,
+ '#ajax' => TRUE,
+ '#limit_validation_errors' => array(),
+ '#default_value' => $instance['settings']['handler_settings']['sort']['field'],
+ );
+
+ $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']['field'] != '_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'],
+ );
+ }
+
+ $form['auto_create'] = array(
+ '#type' => 'checkbox',
+ '#title' => t("Create referenced entities if they don't already exist"),
+ '#default_value' => $instance['settings']['handler_settings']['auto_create'],
+ );
+
+ return $form;
+ }
+
+ /**
+ * Implements SelectionInterface::getReferencableEntities().
+ */
+ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+ $target_type = $this->field['settings']['target_type'];
+
+ $query = $this->buildEntityQuery($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->buildEntityQuery($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->buildEntityQuery();
+ $result = $query
+ ->condition($entity_info['entity_keys']['id'], $ids, 'IN')
+ ->execute();
+ }
+
+ return $result;
+ }
+
+ /**
+ * Implements SelectionInterface::validateAutocompleteInput().
+ */
+ public function validateAutocompleteInput($input, &$element, &$form_state, $form, $strict = TRUE) {
+ $entities = $this->getReferencableEntities($input, '=', 6);
+ $params = array(
+ '%value' => $input,
+ '@value' => $input,
+ );
+ if (empty($entities)) {
+ if ($strict) {
+ // Error if there are no entities available for a required field.
+ form_error($element, t('There are no entities matching "%value".', $params));
+ }
+ }
+ elseif (count($entities) > 5) {
+ $params['@id'] = key($entities);
+ // 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)".', $params));
+ }
+ 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 . ')';
+ }
+ $params['@id'] = $id;
+ form_error($element, t('Multiple entities match this reference; "%multiple". Specify the one you want by appending the id in parentheses, like "@value (@id)".', array('%multiple' => implode('", "', $multiples))));
+ }
+ else {
+ // Take the one and only matching entity.
+ return key($entities);
+ }
+ }
+
+ /**
+ * Builds an EntityQuery to get referencable entities.
+ *
+ * @param string|null $match
+ * (Optional) Text to match the label against. Defaults to NULL.
+ * @param string $match_operator
+ * (Optional) The operation the matching should be done with. Defaults
+ * to "CONTAINS".
+ *
+ * @return \Drupal\Core\Entity\Query\QueryInterface
+ * The EntityQuery object with the basic conditions and sorting applied to
+ * it.
+ */
+ public function buildEntityQuery($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'])) {
+ // @todo: Taxonomy term's bundle key is vocabulary_machine_name, but
+ // entity_query() fails with it, so for now hardcode the vid, until
+ // http://drupal.org/node/1552396 is fixed.
+ $bundle_key = $target_type != 'taxonomy_term' ? $entity_info['entity_keys']['bundle'] : 'vid';
+ $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['field'] != '_none') {
+ $query->sort($sort_settings['field'], $sort_settings['direction']);
+ }
+ }
+
+ return $query;
+ }
+
+ /**
+ * Implements SelectionInterface::entityQueryAlter().
+ */
+ public function entityQueryAlter(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/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
new file mode 100644
index 0000000..ecf3e6f
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
@@ -0,0 +1,119 @@
+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 RecursiveRenderingException(format_string('Recursive rendering detected when rendering entity @entity_type(@entity_id). Aborting rendering.', array('@entity_type' => $entity_type, '@entity_id' => $item['target_id'])));
+ }
+
+ if (!empty($item['entity'])) {
+ $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;
+ }
+ }
+ else {
+ // This is an "auto_create" item.
+ $elements[$delta] = array('#markup' => $item['label']);
+ }
+ $depth = 0;
+ }
+
+ return $elements;
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php
new file mode 100644
index 0000000..ed8dc2e
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php
@@ -0,0 +1,118 @@
+ $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) {
+ $rekey = FALSE;
+ 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 ($item['target_id'] != 'auto_create') {
+ if (!isset($target_entities[$identifier])) {
+ // The entity no longer exists, so remove the key.
+ $rekey = TRUE;
+ unset($items[$id][$delta]);
+ continue;
+ }
+
+ $entity = $target_entities[$identifier];
+ $items[$id][$delta]['entity'] = $entity;
+
+ // @todo: Improve when we have entity_access().
+ $entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE;
+ if (!$entity_access) {
+ continue;
+ }
+ }
+ else {
+ // This is an "auto_create" item, so allow access to it, as the entity doesn't
+ // exists yet, and we are probably in a preview.
+ $items[$id][$delta]['entity'] = FALSE;
+ // Add the label as a special key, as we cannot use entity_label().
+ $items[$id][$delta]['label'] = $item['label'];
+ }
+
+ // Mark item as accessible.
+ $items[$id][$delta]['access'] = TRUE;
+ }
+
+ if ($rekey) {
+ // Rekey the items array.
+ $items[$id] = array_values($items[$id]);
+ }
+ }
+ }
+
+ /**
+ * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::viewElements().
+ *
+ * @see Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+ */
+ 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/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php
new file mode 100644
index 0000000..263a24e
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php
@@ -0,0 +1,44 @@
+ $item) {
+ if (!empty($item['entity'])) {
+ $elements[$delta] = array('#markup' => check_plain($item['target_id']));
+ }
+ }
+
+ return $elements;
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
new file mode 100644
index 0000000..dce40e2
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
@@ -0,0 +1,90 @@
+ 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) {
+ if ($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(
+ '#type' => 'link',
+ '#title' => $label,
+ '#href' => $uri['path'],
+ '#options' => $uri['options'],
+ );
+ }
+ else {
+ $elements[$delta] = array('#markup' => check_plain($label));
+ }
+ }
+ else {
+ // This is an "auto_create" item.
+ $elements[$delta] = array('#markup' => $item['label']);
+ }
+ }
+
+ return $elements;
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php
new file mode 100644
index 0000000..c19b8a6
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php
@@ -0,0 +1,80 @@
+prepareElement($items, $delta, $element, $langcode, $form, $form_state);
+ }
+
+ /**
+ * 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.
+ $handler = entity_reference_get_selection_handler($this->field, $this->instance);
+ $entity_info = entity_get_info($this->field['settings']['target_type']);
+ $auto_create = isset($this->instance['settings']['handler_settings']['auto_create']) ? $this->instance['settings']['handler_settings']['auto_create'] : FALSE;
+
+ if (!empty($element['#value'])) {
+ $entities = drupal_explode_tags($element['#value']);
+ $value = array();
+ foreach ($entities as $entity) {
+ $match = FALSE;
+
+ // Take "label (entity id)', match the id from parenthesis.
+ if (preg_match("/.+\((\d+)\)/", $entity, $matches)) {
+ $match = $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.
+ $match = $handler->validateAutocompleteInput($entity, $element, $form_state, $form, !$auto_create);
+ }
+
+ if ($match) {
+ $value[] = array('target_id' => $match);
+ }
+ elseif ($auto_create && (count($this->instance['settings']['handler_settings']['target_bundles']) == 1 || count($entity_info['bundles']) == 1)) {
+ // Auto-create item. see entity_reference_field_presave().
+ $value[] = array('target_id' => 'auto_create', 'label' => $entity);
+ }
+ }
+ }
+ form_set_value($element, $value, $form_state);
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php
new file mode 100644
index 0000000..2663bdb
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php
@@ -0,0 +1,92 @@
+prepareElement($items, $delta, $element, $langcode, $form, $form_state);
+ return array('target_id' => $element);
+ }
+
+ /**
+ * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate()
+ */
+ public function elementValidate($element, &$form_state, $form) {
+ $auto_create = isset($this->instance['settings']['handler_settings']['auto_create']) ? $this->instance['settings']['handler_settings']['auto_create'] : FALSE;
+
+ // 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, !$auto_create);
+ }
+
+ if (!$value && $auto_create && (count($this->instance['settings']['handler_settings']['target_bundles']) == 1 || count($entity_info['bundles']) == 1)) {
+ // Auto-create item. see entity_reference_field_presave().
+ $value = array(
+ 'target_id' => 'auto_create',
+ 'label' => $element['#value'],
+ // Keep the weight property.
+ '_weight' => $element['#weight'],
+ );
+ // Change the element['#parents'], so in form_set_value() we
+ // populate the correct key.
+ array_pop($element['#parents']);
+ }
+ }
+ form_set_value($element, $value, $form_state);
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php
new file mode 100644
index 0000000..5ffd0f9
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php
@@ -0,0 +1,132 @@
+ '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,
+ );
+
+ $element['placeholder'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Placeholder'),
+ '#default_value' => $this->getSetting('placeholder'),
+ '#description' => t('The placeholder is a short hint (a word or short phrase) intended to aid the user with data entry. A hint could be a sample value or a brief description of the expected format.'),
+ );
+
+
+ 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) {
+ $instance = $this->instance;
+ $field = $this->field;
+ $entity = isset($element['#entity']) ? $element['#entity'] : NULL;
+
+ // Prepare the autocomplete path.
+ $autocomplete_path = $this->getSetting('autocomplete_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 && $entity_id = $entity->id()) {
+ $id = $entity_id;
+ }
+ $autocomplete_path .= $id;
+
+ $element += array(
+ '#type' => 'textfield',
+ '#maxlength' => 1024,
+ '#default_value' => implode(', ', $this->getLabels($items)),
+ '#autocomplete_path' => $autocomplete_path,
+ '#size' => $this->getSetting('size'),
+ '#placeholder' => $this->getSetting('placeholder'),
+ '#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/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php
new file mode 100644
index 0000000..9327aa5
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php
@@ -0,0 +1,183 @@
+ '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::optionsSummary().
+ *
+ * Disable 'cache' and 'title' so it won't be changed.
+ */
+ public function optionsSummary(&$categories, &$options) {
+ parent::optionsSummary($categories, $options);
+ unset($options['query']);
+ unset($options['title']);
+ }
+
+ /**
+ * 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) && $this->view->style_plugin->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() {
+ if (!empty($this->view->live_preview)) {
+ return;
+ }
+
+ // Make sure the id field is included in the results.
+ $id_field = $this->view->storage->get('base_field');
+ $this->id_field_alias = $this->view->query->add_field($this->view->storage->get('base_table'), $id_field);
+
+ $options = $this->getOption('entity_reference_options');
+
+ // 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/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php
new file mode 100644
index 0000000..7e3a970
--- /dev/null
+++ b/core/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/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php
new file mode 100644
index 0000000..c15c2ae
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php
@@ -0,0 +1,120 @@
+ NULL);
+
+ return $options;
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::buildOptionsForm().
+ */
+ public function buildOptionsForm(&$form, &$form_state) {
+ parent::buildOptionsForm($form, $form_state);
+
+ $options = $this->displayHandler->getFieldLabels(TRUE);
+ $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() {
+ if (!empty($this->view->live_preview)) {
+ 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->view->storage->get('base_field');
+
+ // @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.
+ $output = $this->row_plugin->render($values);
+ $output = drupal_render($output);
+ $results[$values->{$id_field_alias}] = filter_xss_admin(preg_replace('/\s\s+/', ' ', str_replace("\n", '', $output)));
+ $this->view->row_index++;
+ }
+ }
+ unset($this->view->row_index);
+ return $results;
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\display\PathPluginBase::preview().
+ */
+ public function preview() {
+ if (!empty($this->view->live_preview)) {
+ return '' . check_plain($this->view->render()) . '
';
+ }
+
+ return $this->view->render();
+ }
+
+ /**
+ * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::even_empty().
+ */
+ function even_empty() {
+ return TRUE;
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/RecursiveRenderingException.php b/core/modules/entity_reference/lib/Drupal/entity_reference/RecursiveRenderingException.php
new file mode 100644
index 0000000..e0fce9c
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/RecursiveRenderingException.php
@@ -0,0 +1,14 @@
+ '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]', 'base');
+
+ // The base handler settings should be displayed.
+ $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.
+ // Option 0: no sort.
+ $this->assertFieldByName('instance[settings][handler_settings][sort][field]', '_none');
+ $this->assertNoFieldByName('instance[settings][handler_settings][sort][direction]');
+ // Option 1: sort by field.
+ $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][field]' => 'nid'), '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][field]' => '_none'), 'instance[settings][handler_settings][sort][field]');
+
+ // 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/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutoCreateTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutoCreateTest.php
new file mode 100644
index 0000000..7ea85c6
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutoCreateTest.php
@@ -0,0 +1,111 @@
+ 'Entity reference auto-create',
+ 'description' => 'Tests creating new entity (e.g. taxonomy-term) from an autocomplete widget.',
+ 'group' => 'Entity Reference',
+ );
+ }
+
+ public static $modules = array('entity_reference', 'node');
+
+ function setUp() {
+ parent::setUp();
+
+ // Create a "referecning" and "referenced" node types.
+ $referencing = $this->drupalCreateContentType();
+ $this->referencing_type = $referencing->type;
+
+ $referenced = $this->drupalCreateContentType();
+ $this->referenced_type = $referenced->type;
+
+ $field = array(
+ 'translatable' => FALSE,
+ 'entity_types' => array(),
+ 'settings' => array(
+ 'target_type' => 'node',
+ ),
+ 'field_name' => 'test_field',
+ 'type' => 'entity_reference',
+ 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+ );
+
+ field_create_field($field);
+
+ $instance = array(
+ 'label' => 'Entity reference field',
+ 'field_name' => 'test_field',
+ 'entity_type' => 'node',
+ 'bundle' => $referencing->type,
+ 'settings' => array(
+ 'handler' => 'base',
+ 'handler_settings' => array(
+ // Reference a single vocabulary.
+ 'target_bundles' => array(
+ $referenced->type,
+ ),
+ // Enable auto-create.
+ 'auto_create' => TRUE,
+ ),
+ ),
+ );
+
+ field_create_instance($instance);
+ }
+
+ /**
+ * Assert creation on a new entity.
+ */
+ public function testAutoCreate() {
+ $user1 = $this->drupalCreateUser(array('access content', "create $this->referencing_type content"));
+ $this->drupalLogin($user1);
+
+ $new_title = $this->randomName();
+
+ // Assert referenced node does not exist.
+ $base_query = entity_query('node');
+ $base_query
+ ->condition('type', $this->referenced_type)
+ ->condition('title', $new_title);
+
+ $query = clone $base_query;
+ $result = $query->execute();
+ $this->assertFalse($result, 'Referenced node does not exist yet.');
+
+ $edit = array(
+ 'title' => $this->randomName(),
+ 'test_field[und][0][target_id]' => $new_title,
+ );
+ $this->drupalPost("node/add/$this->referencing_type", $edit, 'Save');
+
+ // Assert referenced node was created.
+ $query = clone $base_query;
+ $result = $query->execute();
+ $this->assertTrue($result, 'Referenced node was created.');
+ $referenced_nid = key($result);
+
+ // Assert the referenced node is associated with referencing node.
+ $result = entity_query('node')
+ ->condition('type', $this->referencing_type)
+ ->execute();
+
+ $referencing_nid = key($result);
+ $referencing_node = node_load($referencing_nid);
+ $this->assertEqual($referenced_nid, $referencing_node->test_field[LANGUAGE_NOT_SPECIFIED][0]['target_id'], 'Newly created node is referenced from the referencing node.');
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutocompleteTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutocompleteTest.php
new file mode 100644
index 0000000..fb4b4df
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutocompleteTest.php
@@ -0,0 +1,114 @@
+ 'Autocomplete',
+ 'description' => 'Tests autocomplete menu item.',
+ 'group' => 'Entity Reference',
+ );
+ }
+
+ function setUp() {
+ parent::setUp();
+
+ $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
+ $this->drupalLogin($this->admin_user);
+ $this->vocabulary = $this->createVocabulary();
+
+ $this->field_name = 'taxonomy_' . $this->vocabulary->id();
+
+ $field = array(
+ 'field_name' => $this->field_name,
+ 'type' => 'entity_reference',
+ 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+ 'settings' => array(
+ 'target_type' => 'taxonomy_term',
+ ),
+ );
+ field_create_field($field);
+
+ $this->instance = array(
+ 'field_name' => $this->field_name,
+ 'bundle' => 'article',
+ 'entity_type' => 'node',
+ 'widget' => array(
+ 'type' => 'options_select',
+ ),
+ 'settings' => array(
+ 'handler' => 'base',
+ 'handler_settings' => array(
+ 'target_bundles' => array(
+ $this->vocabulary->id(),
+ ),
+ 'auto_create' => TRUE,
+ ),
+ ),
+ );
+ field_create_instance($this->instance);
+ entity_get_display('node', 'article', 'default')
+ ->setComponent($this->instance['field_name'], array(
+ 'type' => 'entity_reference_label',
+ ))
+ ->save();
+ }
+
+ /**
+ * Tests autocompletion edge cases with slashes in the names.
+ */
+ function testTermAutocompletion() {
+ // Add a term with a slash in the name.
+ $first_term = $this->createTerm($this->vocabulary);
+ $first_term->name = '10/16/2011';
+ taxonomy_term_save($first_term);
+ // Add another term that differs after the slash character.
+ $second_term = $this->createTerm($this->vocabulary);
+ $second_term->name = '10/17/2011';
+ taxonomy_term_save($second_term);
+ // Add another term that has both a comma and a slash character.
+ $third_term = $this->createTerm($this->vocabulary);
+ $third_term->name = 'term with, a comma and / a slash';
+ taxonomy_term_save($third_term);
+
+ // Set the path prefix to point to entity reference's autocomplete path.
+ $path_prefix = 'entity_reference/autocomplete/single/' . $this->field_name . '/node/article/NULL';
+
+ // Try to autocomplete a term name that matches both terms.
+ // We should get both term in a json encoded string.
+ $input = '10/';
+ $result = $this->drupalGet($path_prefix, array('query' => array('q' => $input)));
+ $data = drupal_json_decode($result);
+ $this->assertEqual(strip_tags($data[$first_term->name. ' (1)']), check_plain($first_term->name), 'Autocomplete returned the first matching term');
+ $this->assertEqual(strip_tags($data[$second_term->name. ' (2)']), check_plain($second_term->name), 'Autocomplete returned the second matching term');
+
+ // Try to autocomplete a term name that matches first term.
+ // We should only get the first term in a json encoded string.
+ $input = '10/16';
+ $this->drupalGet($path_prefix, array('query' => array('q' => $input)));
+ $target = array($first_term->name . ' (1)' => '' . check_plain($first_term->name) . '
');
+ $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns only the expected matching term.');
+
+ // Try to autocomplete a term name with both a comma and a slash.
+ $input = '"term with, comma and / a';
+ $this->drupalGet($path_prefix, array('query' => array('q' => $input)));
+ $n = $third_term->name;
+ // Term names containing commas or quotes must be wrapped in quotes.
+ if (strpos($third_term->name, ',') !== FALSE || strpos($third_term->name, '"') !== FALSE) {
+ $n = '"' . str_replace('"', '""', $third_term->name) . ' (3)"';
+ }
+ $target = array($n => '' . check_plain($third_term->name) . '
');
+ $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns a term containing a comma and a slash.');
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceItemTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceItemTest.php
new file mode 100644
index 0000000..ab6a6c3
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceItemTest.php
@@ -0,0 +1,103 @@
+ 'Entity reference field API',
+ 'description' => 'Tests using entity fields of the entity-reference field type.',
+ 'group' => 'Entity Reference',
+ );
+ }
+
+ public function setUp() {
+ parent::setUp();
+
+ $field = array(
+ 'translatable' => FALSE,
+ 'entity_types' => array(),
+ 'settings' => array(
+ 'target_type' => 'node',
+ ),
+ 'field_name' => 'field_test',
+ 'type' => 'entity_reference',
+ 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+ );
+
+ field_create_field($field);
+
+ $instance = array(
+ 'entity_type' => 'entity_test',
+ 'field_name' => 'field_test',
+ 'bundle' => 'entity_test',
+ 'widget' => array(
+ 'type' => 'options_select',
+ ),
+ 'settings' => array(
+ 'handler' => 'base',
+ 'handler_settings' => array(),
+ ),
+ );
+ field_create_instance($instance);
+ }
+
+ /**
+ * Tests using entity fields of the taxonomy term reference field type.
+ */
+ public function testEntityReferenceItem() {
+ // Create a node.
+ $node1 = $this->drupalCreateNode();
+ $nid = $node1->id();
+
+ // Just being able to create the entity like this verifies a lot of
+ // code.
+ $entity = entity_create('entity_test', array('name' => 'foo'));
+ $entity->field_test->target_id = $nid;
+ $entity->save();
+
+ $this->assertTrue($entity->field_test instanceof FieldInterface, 'Field implements interface.');
+ $this->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
+ $this->assertEqual($entity->field_test->target_id, $nid);
+ $this->assertEqual($entity->field_test->entity->title, $node1->label());
+ $this->assertEqual($entity->field_test->entity->id(), $nid);
+ $this->assertEqual($entity->field_test->entity->uuid(), $node1->uuid());
+
+ // Change the name of the term via the reference.
+ $new_name = $this->randomName();
+ $entity->field_test->entity->title = $new_name;
+ $entity->field_test->entity->save();
+
+ // Verify it is the correct name.
+ $node = node_load($nid);
+ $this->assertEqual($node->label(), $new_name);
+
+ // Make sure the computed node reflects updates to the node id.
+ $node2 = $this->drupalCreateNode();
+
+ $entity->field_test->target_id = $node2->nid;
+ $this->assertEqual($entity->field_test->entity->id(), $node2->id());
+ $this->assertEqual($entity->field_test->entity->title, $node2->label());
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php
new file mode 100644
index 0000000..d6c958d
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php
@@ -0,0 +1,495 @@
+ 'Entity reference handlers',
+ 'description' => 'Tests for the base 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.
+ $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' => 'base',
+ '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' => 'base',
+ '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' => 'base',
+ '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->value => $comment_labels['published_published'],
+ ),
+ ),
+ ),
+ array(
+ 'arguments' => array(
+ array('Published', 'CONTAINS'),
+ ),
+ 'result' => array(
+ 'comment_node_article' => array(
+ $comments['published_published']->cid->value => $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->value => $comment_labels['published_published'],
+ $comments['published_unpublished']->cid->value => $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->value => $comment_labels['published_published'],
+ $comments['published_unpublished']->cid->value => $comment_labels['published_unpublished'],
+ $comments['unpublished_published']->cid->value => $comment_labels['unpublished_published'],
+ ),
+ ),
+ ),
+ );
+ $this->assertReferencable($field, $instance, $referencable_tests, 'Comment handler (comment + node admin)');
+ }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php
new file mode 100644
index 0000000..fa0a39d
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php
@@ -0,0 +1,150 @@
+ '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.
+ $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' => 'entity_reference',
+ 'cardinality' => 1,
+ );
+
+ $instance = array(
+ 'settings' => array(
+ 'handler' => 'base',
+ 'handler_settings' => array(
+ 'target_bundles' => array(),
+ // Add sorting.
+ 'sort' => array(
+ '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['settings']['handler_settings']['sort'] = array(
+ 'field' => 'nid',
+ 'direction' => 'ASC',
+ );
+ $handler = entity_reference_get_selection_handler($field, $instance);
+ $result = $handler->getReferencableEntities();
+ $expected_result = array(
+ $nodes['published1']->nid => $node_labels['published1'],
+ $nodes['published2']->nid => $node_labels['published2'],
+ );
+ $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.');
+ }
+}
diff --git a/core/modules/entity_reference/tests/modules/entity_reference_test/config/views.view.test_entity_reference.yml b/core/modules/entity_reference/tests/modules/entity_reference_test/config/views.view.test_entity_reference.yml
new file mode 100644
index 0000000..2916abe
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/entity_reference_test/config/views.view.test_entity_reference.yml
@@ -0,0 +1,79 @@
+api_version: '3.0'
+base_field: nid
+base_table: node
+core: 8.x
+description: ''
+disabled: '0'
+display:
+ default:
+ display_plugin: default
+ id: default
+ display_title: Master
+ position: ''
+ display_options:
+ access:
+ type: perm
+ cache:
+ type: none
+ query:
+ type: views_query
+ exposed_form:
+ type: basic
+ pager:
+ type: full
+ style:
+ type: default
+ row:
+ type: fields
+ fields:
+ title:
+ id: title
+ table: node
+ field: title
+ label: ''
+ alter:
+ alter_text: '0'
+ make_link: '0'
+ absolute: '0'
+ trim: '0'
+ word_boundary: '0'
+ ellipsis: '0'
+ strip_tags: '0'
+ html: '0'
+ hide_empty: '0'
+ empty_zero: '0'
+ link_to_node: '1'
+ filters:
+ status:
+ value: '1'
+ table: node
+ field: status
+ id: status
+ expose:
+ operator: '0'
+ group: '1'
+ sorts:
+ created:
+ id: created
+ table: node
+ field: created
+ order: DESC
+ entity_reference_1:
+ display_plugin: entity_reference
+ id: entity_reference_1
+ display_title: EntityReference
+ position: ''
+ display_options:
+ style:
+ type: entity_reference
+ options:
+ grouping: { }
+ search_fields:
+ title: title
+ pager:
+ type: none
+ options:
+ offset: '0'
+human_name: 'Entity reference'
+name: test_entity_reference
+tag: ''
diff --git a/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.info b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.info
new file mode 100644
index 0000000..32b6452
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.info
@@ -0,0 +1,7 @@
+name = "Entity reference Test"
+description = "Support module for the Entity reference tests."
+core = 8.x
+dependencies[] = entity_reference
+package = Testing
+version = VERSION
+hidden = TRUE
diff --git a/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.module b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.module
new file mode 100644
index 0000000..6bbe7e9
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.module
@@ -0,0 +1,6 @@
+ $item) {
$term = $item['taxonomy_term'];
if (!empty($term->rdf_mapping['rdftype'])) {
diff --git a/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php b/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php
index bf02e2b..c7c9984 100644
--- a/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php
+++ b/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php
@@ -95,7 +95,7 @@ function addField($field, $type, $langcode) {
// field), a field API field (a configurable field).
$specifier = $specifiers[$key];
// First, check for field API fields by trying to retrieve the field specified.
- // Normally it is a field name, but field_purge_batch() is passing in
+ // Normally it is a field name, but field_purge_batch() is passing in
// id:$field_id so check that first.
if (substr($specifier, 0, 3) == 'id:') {
$field = field_info_field_by_id(substr($specifier, 3));
@@ -125,9 +125,11 @@ function addField($field, $type, $langcode) {
// also use the property definitions for column.
if ($key < $count) {
$relationship_specifier = $specifiers[$key + 1];
- $propertyDefinitions = typed_data()
- ->create(array('type' => $field['type'] . '_field'))
- ->getPropertyDefinitions();
+
+ // Get the field definitions form a mocked entity.
+ $entity = entity_create($entity_type, array());
+ $propertyDefinitions = $entity->{$field['field_name']}->getPropertyDefinitions();
+
// If the column is not yet known, ie. the
// $node->field_image->entity case then use the id source as the
// column.
diff --git a/core/modules/file/lib/Drupal/file/Plugin/entity_reference/selection/FileSelection.php b/core/modules/file/lib/Drupal/file/Plugin/entity_reference/selection/FileSelection.php
new file mode 100644
index 0000000..1f46441
--- /dev/null
+++ b/core/modules/file/lib/Drupal/file/Plugin/entity_reference/selection/FileSelection.php
@@ -0,0 +1,36 @@
+condition('status', FILE_STATUS_PERMANENT);
+ }
+}
diff --git a/core/modules/forum/forum.module b/core/modules/forum/forum.module
index e9cd043..5bf164d 100644
--- a/core/modules/forum/forum.module
+++ b/core/modules/forum/forum.module
@@ -484,7 +484,7 @@ function forum_taxonomy_term_delete(Term $term) {
* comment_save() calls hook_comment_publish() for all published comments.
*/
function forum_comment_publish($comment) {
- _forum_update_forum_index($comment->nid->value);
+ _forum_update_forum_index($comment->nid->target_id);
}
/**
@@ -497,7 +497,7 @@ function forum_comment_update($comment) {
// comment_save() calls hook_comment_publish() for all published comments,
// so we need to handle all other values here.
if (!$comment->status->value) {
- _forum_update_forum_index($comment->nid->value);
+ _forum_update_forum_index($comment->nid->target_id);
}
}
@@ -505,14 +505,14 @@ function forum_comment_update($comment) {
* Implements hook_comment_unpublish().
*/
function forum_comment_unpublish($comment) {
- _forum_update_forum_index($comment->nid->value);
+ _forum_update_forum_index($comment->nid->target_id);
}
/**
* Implements hook_comment_delete().
*/
function forum_comment_delete($comment) {
- _forum_update_forum_index($comment->nid->value);
+ _forum_update_forum_index($comment->nid->target_id);
}
/**
diff --git a/core/modules/node/lib/Drupal/node/Plugin/entity_reference/selection/NodeSelection.php b/core/modules/node/lib/Drupal/node/Plugin/entity_reference/selection/NodeSelection.php
new file mode 100644
index 0000000..c785af9
--- /dev/null
+++ b/core/modules/node/lib/Drupal/node/Plugin/entity_reference/selection/NodeSelection.php
@@ -0,0 +1,44 @@
+condition('status', NODE_PUBLISHED);
+ }
+ return $query;
+ }
+}
diff --git a/core/modules/options/options.module b/core/modules/options/options.module
index c63f364..f1639ca 100644
--- a/core/modules/options/options.module
+++ b/core/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/rdf/rdf.module b/core/modules/rdf/rdf.module
index cff64e5..af7d157 100644
--- a/core/modules/rdf/rdf.module
+++ b/core/modules/rdf/rdf.module
@@ -419,9 +419,9 @@ function rdf_comment_load($comments) {
// isn't needed until rdf_preprocess_comment() is called, but set it here
// to optimize performance for websites that implement an entity cache.
$comment->rdf_data['date'] = rdf_rdfa_attributes($comment->rdf_mapping['created'], $comment->created->value);
- $comment->rdf_data['nid_uri'] = url('node/' . $comment->nid->value);
- if ($comment->pid->value) {
- $comment->rdf_data['pid_uri'] = url('comment/' . $comment->pid->value, array('fragment' => 'comment-' . $comment->pid->value));
+ $comment->rdf_data['nid_uri'] = url('node/' . $comment->nid->target_id);
+ if ($comment->pid->target_id) {
+ $comment->rdf_data['pid_uri'] = url('comment/' . $comment->pid->target_id, array('fragment' => 'comment-' . $comment->pid->target_id));
}
}
}
@@ -748,7 +748,7 @@ function rdf_preprocess_comment(&$variables) {
$variables['rdf_metadata_attributes'][] = $parent_node_attributes;
// Adds the relation to parent comment, if it exists.
- if ($comment->pid->value != 0) {
+ if ($comment->pid->target_id != 0) {
$parent_comment_attributes['rel'] = $comment->rdf_mapping['pid']['predicates'];
// The parent comment URI is precomputed as part of the rdf_data so that
// it can be cached as part of the entity.
diff --git a/core/modules/search/search.module b/core/modules/search/search.module
index a465e3a..5c67997 100644
--- a/core/modules/search/search.module
+++ b/core/modules/search/search.module
@@ -810,7 +810,7 @@ function search_node_update(Node $node) {
*/
function search_comment_insert($comment) {
// Reindex the node when comments are added.
- search_touch_node($comment->nid->value);
+ search_touch_node($comment->nid->target_id);
}
/**
@@ -818,7 +818,7 @@ function search_comment_insert($comment) {
*/
function search_comment_update($comment) {
// Reindex the node when comments are changed.
- search_touch_node($comment->nid->value);
+ search_touch_node($comment->nid->target_id);
}
/**
@@ -826,7 +826,7 @@ function search_comment_update($comment) {
*/
function search_comment_delete($comment) {
// Reindex the node when comments are deleted.
- search_touch_node($comment->nid->value);
+ search_touch_node($comment->nid->target_id);
}
/**
@@ -834,7 +834,7 @@ function search_comment_delete($comment) {
*/
function search_comment_publish($comment) {
// Reindex the node when comments are published.
- search_touch_node($comment->nid->value);
+ search_touch_node($comment->nid->target_id);
}
/**
@@ -842,7 +842,7 @@ function search_comment_publish($comment) {
*/
function search_comment_unpublish($comment) {
// Reindex the node when comments are unpublished.
- search_touch_node($comment->nid->value);
+ search_touch_node($comment->nid->target_id);
}
/**
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php
index f01d440..2a98ffa 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php
@@ -2,7 +2,7 @@
/**
* @file
- * Definition of Drupal\Core\Entity\Tests\EntityFieldTest.
+ * Definition of Drupal\system\Tests\Entity\EntityFieldTest.
*/
namespace Drupal\system\Tests\Entity;
@@ -46,7 +46,7 @@ protected function createTestEntity($entity_type) {
// Pass in the value of the name field when creating. With the user
// field we test setting a field after creation.
$entity = entity_create($entity_type, array());
- $entity->user_id->value = $this->entity_user->uid;
+ $entity->user_id->target_id = $this->entity_user->uid;
$entity->name->value = $this->entity_name;
// Set a value for the test field.
@@ -96,26 +96,26 @@ protected function assertReadWrite($entity_type) {
$this->assertTrue($entity->user_id instanceof FieldInterface, format_string('%entity_type: Field implements interface', array('%entity_type' => $entity_type)));
$this->assertTrue($entity->user_id[0] instanceof FieldItemInterface, format_string('%entity_type: Field item implements interface', array('%entity_type' => $entity_type)));
- $this->assertEqual($this->entity_user->uid, $entity->user_id->value, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, format_string('%entity_type: User name can be read.', array('%entity_type' => $entity_type)));
// Change the assigned user by entity.
$new_user = $this->drupalCreateUser();
$entity->user_id->entity = $new_user;
- $this->assertEqual($new_user->uid, $entity->user_id->value, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($new_user->uid, $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual($new_user->name, $entity->user_id->entity->name, format_string('%entity_type: Updated user name value can be read.', array('%entity_type' => $entity_type)));
// Change the assigned user by id.
$new_user = $this->drupalCreateUser();
- $entity->user_id->value = $new_user->uid;
- $this->assertEqual($new_user->uid, $entity->user_id->value, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
+ $entity->user_id->target_id = $new_user->uid;
+ $this->assertEqual($new_user->uid, $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual($new_user->name, $entity->user_id->entity->name, format_string('%entity_type: Updated user name value can be read.', array('%entity_type' => $entity_type)));
// Try unsetting a field.
$entity->name->value = NULL;
- $entity->user_id->value = NULL;
+ $entity->user_id->target_id = NULL;
$this->assertNull($entity->name->value, format_string('%entity_type: Name field is not set.', array('%entity_type' => $entity_type)));
- $this->assertNull($entity->user_id->value, format_string('%entity_type: User ID field is not set.', array('%entity_type' => $entity_type)));
+ $this->assertNull($entity->user_id->target_id, format_string('%entity_type: User ID field is not set.', array('%entity_type' => $entity_type)));
$this->assertNull($entity->user_id->entity, format_string('%entity_type: User entity field is not set.', array('%entity_type' => $entity_type)));
// Test using isset(), empty() and unset().
@@ -186,7 +186,7 @@ protected function assertReadWrite($entity_type) {
$this->entity_name = $this->randomName();
$name_item[0]['value'] = $this->entity_name;
$this->entity_user = $this->drupalCreateUser();
- $user_item[0]['value'] = $this->entity_user->uid;
+ $user_item[0]['target_id'] = $this->entity_user->uid;
$this->entity_field_text = $this->randomName();
$text_item[0]['value'] = $this->entity_field_text;
@@ -196,7 +196,7 @@ protected function assertReadWrite($entity_type) {
'field_test_text' => $text_item,
));
$this->assertEqual($this->entity_name, $entity->name->value, format_string('%entity_type: Name value can be read.', array('%entity_type' => $entity_type)));
- $this->assertEqual($this->entity_user->uid, $entity->user_id->value, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, format_string('%entity_type: User name can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual($this->entity_field_text, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', array('%entity_type' => $entity_type)));
@@ -208,7 +208,7 @@ protected function assertReadWrite($entity_type) {
$this->assertTrue($entity->name !== $entity2->name, format_string('%entity_type: Copying properties results in a different field object.', array('%entity_type' => $entity_type)));
$this->assertEqual($entity->name->value, $entity2->name->value, format_string('%entity_type: Name field copied.', array('%entity_type' => $entity_type)));
- $this->assertEqual($entity->user_id->value, $entity2->user_id->value, format_string('%entity_type: User id field copied.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($entity->user_id->target_id, $entity2->user_id->target_id, format_string('%entity_type: User id field copied.', array('%entity_type' => $entity_type)));
$this->assertEqual($entity->field_test_text->value, $entity2->field_test_text->value, format_string('%entity_type: Text field copied.', array('%entity_type' => $entity_type)));
// Tests adding a value to a field item list.
@@ -259,14 +259,14 @@ protected function assertReadWrite($entity_type) {
$this->assertEqual($entity->name->value, 'foo', format_string('%entity_type: Field value has been set via setPropertyValue() on an entity.', array('%entity_type' => $entity_type)));
// Make sure the user id can be set to zero.
- $user_item[0]['value'] = 0;
+ $user_item[0]['target_id'] = 0;
$entity = entity_create($entity_type, array(
'name' => $name_item,
'user_id' => $user_item,
'field_test_text' => $text_item,
));
- $this->assertNotNull($entity->user_id->value, format_string('%entity_type: User id is not NULL', array('%entity_type' => $entity_type)));
- $this->assertIdentical($entity->user_id->value, 0, format_string('%entity_type: User id has been set to 0', array('%entity_type' => $entity_type)));
+ $this->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', array('%entity_type' => $entity_type)));
+ $this->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', array('%entity_type' => $entity_type)));
// Test setting the ID with the value only.
$entity = entity_create($entity_type, array(
@@ -274,8 +274,8 @@ protected function assertReadWrite($entity_type) {
'user_id' => 0,
'field_test_text' => $text_item,
));
- $this->assertNotNull($entity->user_id->value, format_string('%entity_type: User id is not NULL', array('%entity_type' => $entity_type)));
- $this->assertIdentical($entity->user_id->value, 0, format_string('%entity_type: User id has been set to 0', array('%entity_type' => $entity_type)));
+ $this->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', array('%entity_type' => $entity_type)));
+ $this->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', array('%entity_type' => $entity_type)));
}
/**
@@ -307,7 +307,7 @@ protected function assertSave($entity_type) {
$this->assertTrue(is_string($entity->uuid->value), format_string('%entity_type: UUID value can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual(LANGUAGE_NOT_SPECIFIED, $entity->langcode->value, format_string('%entity_type: Language code can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual(language_load(LANGUAGE_NOT_SPECIFIED), $entity->langcode->language, format_string('%entity_type: Language object can be read.', array('%entity_type' => $entity_type)));
- $this->assertEqual($this->entity_user->uid, $entity->user_id->value, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, format_string('%entity_type: User name can be read.', array('%entity_type' => $entity_type)));
$this->assertEqual($this->entity_field_text, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', array('%entity_type' => $entity_type)));
}
@@ -340,7 +340,7 @@ protected function assertIntrospection($entity_type) {
$wrapped_entity = typed_data()->create($definition);
$definitions = $wrapped_entity->getPropertyDefinitions($definition);
$this->assertEqual($definitions['name']['type'], 'string_field', $entity_type .': Name field found.');
- $this->assertEqual($definitions['user_id']['type'], 'entityreference_field', $entity_type .': User field found.');
+ $this->assertEqual($definitions['user_id']['type'], 'entity_reference_field', $entity_type .': User field found.');
$this->assertEqual($definitions['field_test_text']['type'], 'text_field', $entity_type .': Test-text-field field found.');
// Test introspecting an entity object.
@@ -349,14 +349,14 @@ protected function assertIntrospection($entity_type) {
$definitions = $entity->getPropertyDefinitions();
$this->assertEqual($definitions['name']['type'], 'string_field', $entity_type .': Name field found.');
- $this->assertEqual($definitions['user_id']['type'], 'entityreference_field', $entity_type .': User field found.');
+ $this->assertEqual($definitions['user_id']['type'], 'entity_reference_field', $entity_type .': User field found.');
$this->assertEqual($definitions['field_test_text']['type'], 'text_field', $entity_type .': Test-text-field field found.');
$name_properties = $entity->name->getPropertyDefinitions();
$this->assertEqual($name_properties['value']['type'], 'string', $entity_type .': String value property of the name found.');
$userref_properties = $entity->user_id->getPropertyDefinitions();
- $this->assertEqual($userref_properties['value']['type'], 'integer', $entity_type .': Entity id property of the user found.');
+ $this->assertEqual($userref_properties['target_id']['type'], 'integer', $entity_type .': Entity id property of the user found.');
$this->assertEqual($userref_properties['entity']['type'], 'entity', $entity_type .': Entity reference property of the user found.');
$textfield_properties = $entity->field_test_text->getPropertyDefinitions();
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php
index 4ca53c1..8d5fa81 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php
@@ -109,7 +109,7 @@ protected function setUp() {
$entity = entity_create('entity_test', array());
$entity->name->value = $this->randomName();
$index = $i ? 1 : 0;
- $entity->user_id->value = $this->accounts[$index]->uid;
+ $entity->user_id->target_id = $this->accounts[$index]->uid;
$entity->{$this->fieldName}->tid = $this->terms[$index]->tid;
$entity->save();
$this->entities[] = $entity;
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php
index b658cd9..e5f79c9 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php
@@ -215,13 +215,13 @@ protected function assertMultilingualProperties($entity_type) {
$entity = entity_load($entity_type, $entity->id());
$this->assertEqual($entity->language()->langcode, LANGUAGE_NOT_SPECIFIED, format_string('%entity_type: Entity created as language neutral.', array('%entity_type' => $entity_type)));
$this->assertEqual($name, $entity->getTranslation(LANGUAGE_DEFAULT)->get('name')->value, format_string('%entity_type: The entity name has been correctly stored as language neutral.', array('%entity_type' => $entity_type)));
- $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_DEFAULT)->get('user_id')->value, format_string('%entity_type: The entity author has been correctly stored as language neutral.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_DEFAULT)->get('user_id')->target_id, format_string('%entity_type: The entity author has been correctly stored as language neutral.', array('%entity_type' => $entity_type)));
// As fields, translatable properties should ignore the given langcode and
// use neutral language if the entity is not translatable.
$this->assertEqual($name, $entity->getTranslation($langcode)->get('name')->value, format_string('%entity_type: The entity name defaults to neutral language.', array('%entity_type' => $entity_type)));
- $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->value, format_string('%entity_type: The entity author defaults to neutral language.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->target_id, format_string('%entity_type: The entity author defaults to neutral language.', array('%entity_type' => $entity_type)));
$this->assertEqual($name, $entity->get('name')->value, format_string('%entity_type: The entity name can be retrieved without specifying a language.', array('%entity_type' => $entity_type)));
- $this->assertEqual($uid, $entity->get('user_id')->value, format_string('%entity_type: The entity author can be retrieved without specifying a language.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($uid, $entity->get('user_id')->target_id, format_string('%entity_type: The entity author can be retrieved without specifying a language.', array('%entity_type' => $entity_type)));
// Create a language-aware entity and check that properties are stored
// as language-aware.
@@ -230,13 +230,13 @@ protected function assertMultilingualProperties($entity_type) {
$entity = entity_load($entity_type, $entity->id());
$this->assertEqual($entity->language()->langcode, $langcode, format_string('%entity_type: Entity created as language specific.', array('%entity_type' => $entity_type)));
$this->assertEqual($name, $entity->getTranslation($langcode)->get('name')->value, format_string('%entity_type: The entity name has been correctly stored as a language-aware property.', array('%entity_type' => $entity_type)));
- $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->value, format_string('%entity_type: The entity author has been correctly stored as a language-aware property.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->target_id, format_string('%entity_type: The entity author has been correctly stored as a language-aware property.', array('%entity_type' => $entity_type)));
// Translatable properties on a translatable entity should use default
// language if LANGUAGE_NOT_SPECIFIED is passed.
$this->assertEqual($name, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('name')->value, format_string('%entity_type: The entity name defaults to the default language.', array('%entity_type' => $entity_type)));
- $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('user_id')->value, format_string('%entity_type: The entity author defaults to the default language.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('user_id')->target_id, format_string('%entity_type: The entity author defaults to the default language.', array('%entity_type' => $entity_type)));
$this->assertEqual($name, $entity->get('name')->value, format_string('%entity_type: The entity name can be retrieved without specifying a language.', array('%entity_type' => $entity_type)));
- $this->assertEqual($uid, $entity->get('user_id')->value, format_string('%entity_type: The entity author can be retrieved without specifying a language.', array('%entity_type' => $entity_type)));
+ $this->assertEqual($uid, $entity->get('user_id')->target_id, format_string('%entity_type: The entity author can be retrieved without specifying a language.', array('%entity_type' => $entity_type)));
// Create property translations.
$properties = array();
@@ -266,7 +266,7 @@ protected function assertMultilingualProperties($entity_type) {
'%langcode' => $langcode,
);
$this->assertEqual($properties[$langcode]['name'][0], $entity->getTranslation($langcode)->get('name')->value, format_string('%entity_type: The entity name has been correctly stored for language %langcode.', $args));
- $this->assertEqual($properties[$langcode]['user_id'][0], $entity->getTranslation($langcode)->get('user_id')->value, format_string('%entity_type: The entity author has been correctly stored for language %langcode.', $args));
+ $this->assertEqual($properties[$langcode]['user_id'][0], $entity->getTranslation($langcode)->get('user_id')->target_id, format_string('%entity_type: The entity author has been correctly stored for language %langcode.', $args));
}
// Test query conditions (cache is reset at each call).
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php
index 15220cb..a4e2d4e 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php
@@ -94,7 +94,7 @@ protected function assertCRUD($entity_type) {
$this->assertNotEqual($entity_duplicate->id(), $entity->id());
break;
default:
- $this->assertEqual($entity_duplicate->{$property}->value, $entity->{$property}->value);
+ $this->assertEqual($entity_duplicate->{$property}->getValue(), $entity->{$property}->getValue());
}
}
$entity_duplicate->save();
diff --git a/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php b/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php
index 5fb3c46..86aeff4 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php
@@ -91,7 +91,7 @@ public function testNormalize() {
array('value' => $this->values['name']),
),
'user_id' => array(
- array('value' => $this->values['user_id']),
+ array('target_id' => $this->values['user_id']),
),
'field_test_text' => array(
array(
diff --git a/core/modules/system/system.module b/core/modules/system/system.module
index 336f84b..c7f6395 100644
--- a/core/modules/system/system.module
+++ b/core/modules/system/system.module
@@ -2275,7 +2275,7 @@ function system_data_type_info() {
'class' => '\Drupal\Core\Entity\Field\Type\LanguageItem',
'list class' => '\Drupal\Core\Entity\Field\Type\Field',
),
- 'entityreference_field' => array(
+ 'entity_reference_field' => array(
'label' => t('Entity reference field item'),
'description' => t('An entity field containing an entity reference.'),
'class' => '\Drupal\Core\Entity\Field\Type\EntityReferenceItem',
diff --git a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php
index e1892a0..c08e3b3 100644
--- a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php
+++ b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php
@@ -36,7 +36,7 @@ public function form(array $form, array &$form_state, EntityInterface $entity) {
$form['user_id'] = array(
'#type' => 'textfield',
'#title' => 'UID',
- '#default_value' => $translation->user_id->value,
+ '#default_value' => $translation->user_id->target_id,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
diff --git a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestMulStorageController.php b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestMulStorageController.php
index 28a90ee..786e91a 100644
--- a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestMulStorageController.php
+++ b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestMulStorageController.php
@@ -25,7 +25,7 @@ public function baseFieldDefinitions() {
$fields = parent::baseFieldDefinitions();
$fields['default_langcode'] = array(
'label' => t('Default language'),
- 'description' => t('Flag to inditcate whether this is the default language.'),
+ 'description' => t('Flag to indicate whether this is the default language.'),
'type' => 'boolean_field',
);
return $fields;
diff --git a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php
index 0908700..500a41c 100644
--- a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php
+++ b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php
@@ -46,8 +46,8 @@ public function baseFieldDefinitions() {
$fields['user_id'] = array(
'label' => t('User ID'),
'description' => t('The ID of the associated user.'),
- 'type' => 'entityreference_field',
- 'settings' => array('entity type' => 'user'),
+ 'type' => 'entity_reference_field',
+ 'settings' => array('target_type' => 'user'),
'translatable' => TRUE,
);
return $fields;
diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/entity_reference/selection/TermSelection.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/entity_reference/selection/TermSelection.php
new file mode 100644
index 0000000..df87767
--- /dev/null
+++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/entity_reference/selection/TermSelection.php
@@ -0,0 +1,61 @@
+instance['settings']['handler_settings']['target_bundles']) ? $this->instance['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']);
+
+ foreach ($bundles as $bundle) {
+ if ($vocabulary = entity_load('taxonomy_vocabulary',$bundle)) {
+ if ($terms = taxonomy_get_tree($vocabulary->id(), 0)) {
+ foreach ($terms as $term) {
+ $options[$vocabulary->id()][$term->tid] = str_repeat('-', $term->depth) . check_plain($term->name);
+ }
+ }
+ }
+ }
+
+ return $options;
+ }
+}
diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/formatter/EntityReferenceTaxonomyTermRssFormatter.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/formatter/EntityReferenceTaxonomyTermRssFormatter.php
new file mode 100644
index 0000000..c528985
--- /dev/null
+++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/formatter/EntityReferenceTaxonomyTermRssFormatter.php
@@ -0,0 +1,50 @@
+ $item) {
+ $entity->rss_elements[] = array(
+ 'key' => 'category',
+ 'value' => $item['target_id'] != 'autocreate' ? $item['entity']->label() : $item['label'],
+ 'attributes' => array(
+ 'domain' => $item['target_id'] != 'autocreate' ? url('taxonomy/term/' . $item['target_id'], array('absolute' => TRUE)) : '',
+ ),
+ );
+ }
+
+ return $elements;
+ }
+}
diff --git a/core/modules/tracker/tracker.module b/core/modules/tracker/tracker.module
index d33a878..0eaa7d8 100644
--- a/core/modules/tracker/tracker.module
+++ b/core/modules/tracker/tracker.module
@@ -230,7 +230,7 @@ function tracker_comment_update($comment) {
// comment_save() calls hook_comment_publish() for all published comments
// so we need to handle all other values here.
if ($comment->status->value != COMMENT_PUBLISHED) {
- _tracker_remove($comment->nid->value, $comment->uid->value, $comment->changed->value);
+ _tracker_remove($comment->nid->target_id, $comment->uid->target_id, $comment->changed->value);
}
}
@@ -241,21 +241,21 @@ function tracker_comment_update($comment) {
* comment_save() calls hook_comment_publish() for all published comments.
*/
function tracker_comment_publish($comment) {
- _tracker_add($comment->nid->value, $comment->uid->value, $comment->changed->value);
+ _tracker_add($comment->nid->target_id, $comment->uid->target_id, $comment->changed->value);
}
/**
* Implements hook_comment_unpublish().
*/
function tracker_comment_unpublish($comment) {
- _tracker_remove($comment->nid->value, $comment->uid->value, $comment->changed->value);
+ _tracker_remove($comment->nid->target_id, $comment->uid->target_id, $comment->changed->value);
}
/**
* Implements hook_comment_delete().
*/
function tracker_comment_delete($comment) {
- _tracker_remove($comment->nid->value, $comment->uid->value, $comment->changed->value);
+ _tracker_remove($comment->nid->target_id, $comment->uid->target_id, $comment->changed->value);
}
/**
diff --git a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php
index 42be87c..7e88fb5 100644
--- a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php
+++ b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php
@@ -311,11 +311,12 @@ protected function getTranslation(EntityInterface $entity, $langcode) {
* The property value.
*/
protected function getValue(ComplexDataInterface $translation, $property, $langcode) {
+ $key = $property == 'user_id' ? 'target_id' : 'value';
if (($translation instanceof EntityInterface) && !($translation instanceof EntityNG)) {
- return is_array($translation->$property) ? $translation->{$property}[$langcode][0]['value'] : $translation->$property;
+ return is_array($translation->$property) ? $translation->{$property}[$langcode][0][$key] : $translation->$property;
}
else {
- return $translation->get($property)->value;
+ return $translation->get($property)->{$key};
}
}
diff --git a/core/modules/translation_entity/translation_entity.pages.inc b/core/modules/translation_entity/translation_entity.pages.inc
index e2e76cc..a09e3c4 100644
--- a/core/modules/translation_entity/translation_entity.pages.inc
+++ b/core/modules/translation_entity/translation_entity.pages.inc
@@ -209,9 +209,10 @@ function translation_entity_prepare_translation(EntityInterface $entity, Languag
$source_translation = $entity->getTranslation($source->langcode);
$target_translation = $entity->getTranslation($target->langcode);
foreach ($target_translation->getPropertyDefinitions() as $property_name => $definition) {
- // @todo The value part should not be needed. Remove it as soon as things
- // do not break.
- $target_translation->$property_name->value = $source_translation->$property_name->value;
+ // @todo The "key" part should not be needed. Remove it as soon as things
+ // do not break.
+ $key = key($entity->{$property_name}[0]->getProperties());
+ $target_translation->$property_name->{$key} = $source_translation->$property_name->{$key};
}
}
else {
diff --git a/core/modules/user/lib/Drupal/user/Plugin/entity_reference/selection/UserSelection.php b/core/modules/user/lib/Drupal/user/Plugin/entity_reference/selection/UserSelection.php
new file mode 100644
index 0000000..4a1352b
--- /dev/null
+++ b/core/modules/user/lib/Drupal/user/Plugin/entity_reference/selection/UserSelection.php
@@ -0,0 +1,146 @@
+ array(
+ 'type' => '_none',
+ ),
+ );
+
+ // Add user specific filter options.
+ $form['filter']['type'] = array(
+ '#type' => 'select',
+ '#title' => t('Filter by'),
+ '#options' => array(
+ '_none' => t('- None -'),
+ 'role' => t('User role'),
+ ),
+ '#ajax' => TRUE,
+ '#limit_validation_errors' => array(),
+ '#default_value' => $instance['settings']['handler_settings']['filter']['type'],
+ );
+
+ $form['filter']['settings'] = array(
+ '#type' => 'container',
+ '#attributes' => array('class' => array('entity_reference-settings')),
+ '#process' => array('_entity_reference_form_process_merge_parent'),
+ );
+
+ if ($instance['settings']['handler_settings']['filter']['type'] == 'role') {
+ // Merge-in default values.
+ $instance['settings']['handler_settings']['filter'] += array(
+ 'role' => NULL,
+ );
+
+ $form['filter']['settings']['role'] = array(
+ '#type' => 'checkboxes',
+ '#title' => t('Restrict to the selected roles'),
+ '#required' => TRUE,
+ '#options' => user_roles(TRUE),
+ '#default_value' => $instance['settings']['handler_settings']['filter']['role'],
+ );
+ }
+
+ return $form;
+ }
+
+ /**
+ * Overrides SelectionBase::buildEntityQuery().
+ */
+ public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
+ $query = parent::buildEntityQuery($match, $match_operator);
+
+ // The user entity doesn't have a label column.
+ if (isset($match)) {
+ $query->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::entityQueryAlter().
+ */
+ public function entityQueryAlter(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);
+ }
+ }
+ }
+
+ // Add the filter by role option.
+ if (!empty($this->instance['settings']['handler_settings']['filter'])) {
+ $filter_settings = $this->instance['settings']['handler_settings']['filter'];
+ if ($filter_settings['type'] == 'role') {
+ $tables = $query->getTables();
+ $base_table = $tables['base_table']['alias'];
+ $query->join('users_roles', 'ur', $base_table . '.uid = ur.uid');
+ $query->condition('ur.rid', $filter_settings['role']);
+ }
+ }
+ }
+}
diff --git a/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php
new file mode 100644
index 0000000..a47529e
--- /dev/null
+++ b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php
@@ -0,0 +1,229 @@
+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']) ? array() : $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->get('base_table') == $entity_info['base_table']) {
+ $name = $view->storage->get('name');
+ $display = $view->storage->get('display');
+ $options[$name . ':' . $display_id] = $name . ' - ' . $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['arguments']) ? implode(', ', $view_settings['arguments']) : '';
+ $form['view']['arguments'] = 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|null $match
+ * (Optional) Text to match the label against. Defaults to NULL.
+ * @param string $match_operator
+ * (Optional) The operation the matching should be done with. Defaults
+ * to "CONTAINS".
+ * @param int $limit
+ * Limit the query to a given number of items. Defaults to 0, which
+ * indicates no limiting.
+ * @param array|null $ids
+ * Array of entity IDs. Defaults to NULL.
+ *
+ * @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'];
+ $arguments = $this->instance['settings']['handler_settings']['view']['arguments'];
+ $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->access($display_name)) {
+ throw new ViewsException('The view %view_name is no longer eligible for the %field_name field.', array('%view_name' => $view_name, '%field_name' => $this->instance['label']));
+ }
+ $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->get($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'];
+ $arguments = $this->instance['settings']['handler_settings']['view']['arguments'];
+ $result = array();
+ if ($this->initializeView($match, $match_operator, $limit)) {
+ // Get the results.
+ $result = $this->view->executeDisplay($display_name, $arguments);
+ }
+
+ $return = array();
+ if ($result) {
+ foreach($this->view->result as $row) {
+ $entity = $row->_entity;
+ $return[$entity->bundle()][$entity->id()] = $entity->label();
+ }
+ }
+ 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->pager->get_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'];
+ $arguments = $this->instance['settings']['handler_settings']['view']['arguments'];
+ $result = array();
+ if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
+ // Get the results.
+ $entities = $this->view->executeDisplay($display_name, $arguments);
+ $result = array_keys($entities);
+ }
+ return $result;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::validateAutocompleteInput().
+ */
+ public function validateAutocompleteInput($input, &$element, &$form_state, $form, $strict = TRUE) {
+ return NULL;
+ }
+
+ /**
+ * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::entityQueryAlter().
+ */
+ public function entityQueryAlter(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 'arguments' 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.
+ $arguments_string = trim($element['arguments']['#value']);
+ if ($arguments_string === '') {
+ $arguments = array();
+ }
+ else {
+ // array_map is called to trim whitespaces from the arguments.
+ $arguments = array_map('trim', explode(',', $arguments_string));
+ }
+
+ $value = array('view_name' => $view, 'display_name' => $display, 'arguments' => $arguments);
+ form_set_value($element, $value, $form_state);
+ }
+}
diff --git a/core/modules/views/lib/Drupal/views/Tests/EntityReference/SelectionTest.php b/core/modules/views/lib/Drupal/views/Tests/EntityReference/SelectionTest.php
new file mode 100644
index 0000000..26e2e82
--- /dev/null
+++ b/core/modules/views/lib/Drupal/views/Tests/EntityReference/SelectionTest.php
@@ -0,0 +1,83 @@
+ 'Entity reference selection handler',
+ 'description' => 'Tests entity-reference selection handler provided by Views.',
+ 'group' => 'Views',
+ );
+ }
+
+ /**
+ * Tests the selection handler.
+ */
+ public function testSelectionHandler() {
+ // Create nodes.
+ $type = $this->drupalCreateContentType()->type;
+ $node1 = $this->drupalCreateNode(array('type' => $type));
+ $node2 = $this->drupalCreateNode(array('type' => $type));
+ $node3 = $this->drupalCreateNode();
+
+ $nodes = array();
+ foreach (array($node1, $node2, $node3) as $node) {
+ $nodes[$node->type][$node->nid] = $node->label();
+ }
+
+ // 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' => 'views',
+ 'handler_settings' => array(
+ 'target_bundles' => array(),
+ 'view' => array(
+ 'view_name' => 'test_entity_reference',
+ 'display_name' => 'entity_reference_1',
+ 'arguments' => array(),
+ ),
+ ),
+ ),
+ );
+
+ // Get values from selection handler.
+ $handler = entity_reference_get_selection_handler($field, $instance);
+ $result = $handler->getReferencableEntities();
+
+ $success = FALSE;
+ foreach ($result as $node_type => $values) {
+ foreach ($values as $nid => $label) {
+ if (!$success = $nodes[$node_type][$nid] == trim(strip_tags($label))) {
+ // There was some error, so break.
+ break;
+ }
+ }
+ }
+
+ $this->assertTrue($success, 'Views selection handler returned expected values.');
+ }
+}
diff --git a/core/modules/views/lib/Drupal/views/ViewsException.php b/core/modules/views/lib/Drupal/views/ViewsException.php
new file mode 100644
index 0000000..8085db2
--- /dev/null
+++ b/core/modules/views/lib/Drupal/views/ViewsException.php
@@ -0,0 +1,15 @@
+