diff --git a/core/MAINTAINERS.txt b/core/MAINTAINERS.txt index 574b850..f43fb4c 100644 --- a/core/MAINTAINERS.txt +++ b/core/MAINTAINERS.txt @@ -204,6 +204,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/DatabaseStorageControllerNG.php b/core/lib/Drupal/Core/Entity/DatabaseStorageControllerNG.php index 10a7a77..ad43356 100644 --- a/core/lib/Drupal/Core/Entity/DatabaseStorageControllerNG.php +++ b/core/lib/Drupal/Core/Entity/DatabaseStorageControllerNG.php @@ -154,7 +154,11 @@ protected function mapFromStorageRecords(array $records, $load_revision = FALSE) $entity->setCompatibilityMode(TRUE); foreach ($record as $name => $value) { - $entity->{$name}[LANGUAGE_DEFAULT][0]['value'] = $value; + // @todo: Remove after http://drupal.org/node/1869250 + // gets in. + // see http://drupal.org/node/1847588#comment-6877396 + $key = $name == 'user_id' ? 'target_id' : 'value'; + $entity->{$name}[LANGUAGE_DEFAULT][0][$key] = $value; } $records[$id] = $entity; } @@ -298,7 +302,8 @@ protected function invokeHook($hook, EntityInterface $entity) { protected function mapToStorageRecord(EntityInterface $entity) { $record = new \stdClass(); foreach ($this->entityInfo['schema_fields_sql']['base_table'] as $name) { - $record->$name = $entity->$name->value; + $key = key($entity->$name->offsetGet(0)->getProperties()); + $record->$name = $entity->$name->{$key}; } return $record; } @@ -309,7 +314,8 @@ protected function mapToStorageRecord(EntityInterface $entity) { protected function mapToRevisionStorageRecord(EntityInterface $entity) { $record = new \stdClass(); foreach ($this->entityInfo['schema_fields_sql']['revision_table'] as $name) { - $record->$name = $entity->$name->value; + $key = key($entity->$name->offsetGet(0)->getProperties()); + $record->$name = $entity->$name->{$key}; } return $record; diff --git a/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php b/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php index a60e65e..aff2c90 100644 --- a/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php +++ b/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php @@ -2,19 +2,19 @@ /** * @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\TypedData\ContextAwareInterface; /** - * Defines the 'entityreference_field' entity field item. + * Defines the 'entity_reference' entity field item. * * Required settings (below the definition's 'settings' key) are: - * - entity type: The entity type to reference. + * - target_type: The entity type to reference. */ class EntityReferenceItem extends FieldItemBase { @@ -28,36 +28,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,15 +68,15 @@ 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']); } else { $this->properties['entity']->setValue(isset($values['entity']) ? $values['entity'] : 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.'); } } } 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/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..fcf3ef5 --- /dev/null +++ b/core/modules/entity_reference/entity_reference.module @@ -0,0 +1,539 @@ + 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($entity_type, $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($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) { + $ids = array(); + foreach ($items as $delta => $item) { + if (!entity_reference_field_is_empty($item, $field) && $item['target_id'] !== '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' => 'fieldset', + '#title' => t('Entity selection'), + '#tree' => TRUE, + '#process' => array('_entity_reference_form_process_merge_parent'), + ); + + $form['handler']['handler'] = array( + '#type' => 'select', + '#title' => t('Mode'), + '#options' => $handlers_options, + '#default_value' => $settings['handler'], + '#required' => TRUE, + '#ajax' => TRUE, + '#limit_validation_errors' => array(), + ); + $form['handler']['handler_submit'] = array( + '#type' => 'submit', + '#value' => t('Change handler'), + '#limit_validation_errors' => array(), + '#attributes' => array( + 'class' => array('js-hide'), + ), + '#submit' => array('entity_reference_settings_ajax_submit'), + ); + + $form['handler']['handler_settings'] = array( + '#type' => 'container', + '#attributes' => array('class' => array('entity_reference-settings')), + ); + + $handler = entity_reference_get_selection_handler($field, $instance); + $form['handler']['handler_settings'] += $handler->settingsForm($field, $instance); + + return $form; +} + +/** + * Render API callback: Processes the field instance settings form and allows + * access to the form state. + * + * @see entity_reference_field_instance_settings_form() + */ +function _entity_reference_field_instance_settings_ajax_process($form, $form_state) { + _entity_reference_field_instance_settings_ajax_process_element($form, $form); + return $form; +} + +/** + * Adds entity_reference specific properties to AJAX form elements from the + * field instance settings form. + * + * @see _entity_reference_field_instance_settings_ajax_process() + */ +function _entity_reference_field_instance_settings_ajax_process_element(&$element, $main_form) { + if (!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 'Entity selection' fieldset, we need to go one more level above + // because of our extra container. + if (isset($element['#title']) && $element['#title'] == t('Entity selection')) { + array_pop($parents); + } + $element['#parents'] = $parents; + return $element; +} + +/** + * Form element validation handler; Filters the #value property of an element. + */ +function _entity_reference_element_validate_filter(&$element, &$form_state) { + $element['#value'] = array_filter($element['#value']); + form_set_value($element, $element['#value'], $form_state); +} + +/** + * Form element validation handler; Stores the new values in the form state. + * + * @see entity_reference_field_instance_settings_form() + */ +function _entity_reference_field_instance_settings_validate($form, &$form_state) { + $instance = $form['#instance']; + if (isset($form_state['values']['instance'])) { + $instance['settings'] = $form_state['values']['instance']['settings']; + } + $form_state['entity_reference']['instance'] = $instance; + + unset($form_state['values']['instance']['settings']['handler_submit']); +} + +/** + * Ajax callback for the handler settings form. + * + * @see entity_reference_field_instance_settings_form() + */ +function entity_reference_settings_ajax($form, $form_state) { + $trigger = $form_state['triggering_element']; + return NestedArray::getValue($form, $trigger['#ajax']['element']); +} + +/** + * Submit handler for the non-JS case. + * + * @see entity_reference_field_instance_settings_form() + */ +function entity_reference_settings_ajax_submit($form, &$form_state) { + $form_state['rebuild'] = TRUE; +} + +/** + * Implements hook_options_list(). + */ +function entity_reference_options_list($field, $instance, $entity_type = NULL, $entity = NULL) { + if (!$options = entity_reference_get_selection_handler($field, $instance, $entity)->getReferencableEntities()) { + return array(); + } + + // Rebuild the array by changing the bundle key into the bundle label. + $target_type = $field['settings']['target_type']; + $entity_info = entity_get_info($target_type); + + $return = array(); + foreach ($options as $bundle => $entity_ids) { + $bundle_label = check_plain($entity_info['bundles'][$bundle]['label']); + $return[$bundle_label] = $entity_ids; + } + + return count($return) == 1 ? reset($return) : $return; +} + +/** + * Implements hook_query_TAG_alter(). + */ +function entity_reference_query_entity_reference_alter(AlterableInterface $query) { + $handler = $query->getMetadata('entity_reference_selection_handler'); + $handler->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 ''. + * @param string $string + * The label of the entity to query by. + * + * @return \Symfony\Component\HttpFoundation\JsonResponse + */ +function entity_reference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') { + $field = field_info_field($field_name); + $instance = field_info_instance($entity_type, $field_name, $bundle_name); + + return entity_reference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string); +} + +/** + * Returns JSON data based on a given field, instance and search string. + * + * This function can be used by other modules that wish to pass a mocked + * definition of the field on instance. + * + * @param string $type + * The widget type (i.e. 'single' or 'tags'). + * @param array $field + * The field array definition. + * @param array $instance + * The instance array definition. + * @param string $entity_type + * The entity type. + * @param string $entity_id + * (optional) The entity ID the entity-reference field is attached to. + * Defaults to ''. + * @param string $string + * The label of the entity to query by. + * + * @return \Symfony\Component\HttpFoundation\JsonResponse + * + * @see entity_reference_autocomplete_callback() + */ +function entity_reference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') { + $target_type = $field['settings']['target_type']; + $matches = array(); + $entity = NULL; + + if ($entity_id !== 'NULL') { + $entity = entity_load($entity_type, $entity_id); + // @todo: Improve when we have entity_access(). + $entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE; + if (!$entity || !$entity_access) { + return MENU_ACCESS_DENIED; + } + } + $handler = entity_reference_get_selection_handler($field, $instance, $entity); + + if ($type == 'tags') { + // The user enters a comma-separated list of tags. We only autocomplete the + // last tag. + $tags_typed = drupal_explode_tags($string); + $tag_last = drupal_strtolower(array_pop($tags_typed)); + if (!empty($tag_last)) { + $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : ''; + } + } + else { + // The user enters a single tag. + $prefix = ''; + $tag_last = $string; + } + + if (isset($tag_last)) { + // Get an array of matching entities. + $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10); + + // Loop through the products and convert them into autocomplete output. + foreach ($entity_labels as $values) { + foreach ($values as $entity_id => $label) { + $key = "$label ($entity_id)"; + // Strip things like starting/trailing white spaces, line breaks and + // tags. + $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key))))); + // Names containing commas or quotes must be wrapped in quotes. + if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) { + $key = '"' . str_replace('"', '""', $key) . '"'; + } + $matches[$prefix . $key] = '
' . $label . '
'; + } + } + } + + return new JsonResponse($matches); +} diff --git a/core/modules/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..3ea12f5 --- /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..b91bc99 --- /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..a246866 --- /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..2a27c37 --- /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..2fb8b93 --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php @@ -0,0 +1,341 @@ +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']); + + $default_values = array( + 'handler_settings' => array( + 'target_bundles' => array(), + 'sort' => array( + 'type' => 'none', + ), + 'auto_create' => FALSE, + ), + ); + + $instance['settings'] = NestedArray::mergeDeep($default_values, $instance['settings']); + + if (!empty($entity_info['entity_keys']['bundle'])) { + $bundles = array(); + foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) { + $bundles[$bundle_name] = $bundle_info['label']; + } + + $form['target_bundles'] = array( + '#type' => 'checkboxes', + '#title' => t('Target bundles'), + '#options' => $bundles, + '#default_value' => $instance['settings']['handler_settings']['target_bundles'], + '#size' => 6, + '#multiple' => TRUE, + '#description' => t('The bundles of the entity type that can be referenced. Optional, leave empty for all bundles.'), + '#element_validate' => array('_entity_reference_element_validate_filter'), + ); + } + else { + $form['target_bundles'] = array( + '#type' => 'value', + '#value' => array(), + ); + } + + $form['sort']['type'] = array( + '#type' => 'select', + '#title' => t('Sort by'), + '#options' => array( + 'none' => t("Don't sort"), + 'field' => t('A field of the referenced entity'), + ), + '#ajax' => TRUE, + '#limit_validation_errors' => array(), + '#default_value' => $instance['settings']['handler_settings']['sort']['type'], + ); + + $form['sort']['settings'] = array( + '#type' => 'container', + '#attributes' => array('class' => array('entity_reference-settings')), + '#process' => array('_entity_reference_form_process_merge_parent'), + ); + + if ($instance['settings']['handler_settings']['sort']['type'] == 'field') { + // Merge-in default values. + $instance['settings']['handler_settings']['sort'] += array( + 'field' => NULL, + ); + + // @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']['settings']['field'] = array( + '#type' => 'select', + '#title' => t('Sort field'), + '#required' => TRUE, + '#options' => $fields, + '#default_value' => $instance['settings']['handler_settings']['sort']['field'], + ); + } + + if ($instance['settings']['handler_settings']['sort']['type'] != 'none') { + // Merge-in default values. + $instance['settings']['handler_settings']['sort'] += array( + 'direction' => 'ASC', + ); + + $form['sort']['settings']['direction'] = array( + '#type' => 'select', + '#title' => t('Sort direction'), + '#required' => TRUE, + '#options' => array( + 'ASC' => t('Ascending'), + 'DESC' => t('Descending'), + ), + '#default_value' => $instance['settings']['handler_settings']['sort']['direction'], + ); + } + + $form['auto_create'] = array( + '#type' => 'checkbox', + '#title' => t('Auto-create'), + '#description' => t('Allow creating new entities in autocomplete.'), + '#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['type'] == 'field') { + $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..e32621c --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php @@ -0,0 +1,113 @@ +field['settings']['target_type']); + $options = array(); + if (!empty($entity_info['view modes'])) { + foreach ($entity_info['view modes'] as $view_mode => $view_mode_settings) { + $options[$view_mode] = $view_mode_settings['label']; + } + } + + $elements['view_mode'] = array( + '#type' => 'select', + '#options' => $options, + '#title' => t('View mode'), + '#default_value' => $this->getSetting('view_mode'), + '#required' => TRUE, + ); + + $elements['links'] = array( + '#type' => 'checkbox', + '#title' => t('Show links'), + '#default_value' => $this->getSetting('links'), + ); + + return $elements; + } + + /** + * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::settingsSummary(). + */ + public function settingsSummary() { + $summary = array(); + + $entity_info = entity_get_info($this->field['settings']['target_type']); + $view_mode = $this->getSetting('view_mode'); + $summary[] = t('Rendered as @mode', array('@mode' => isset($entity_info['view modes'][$view_mode]['label']) ? $entity_info['view modes'][$view_mode]['label'] : $view_mode)); + $summary[] = $this->getSetting('links') ? t('Display links') : t('Do not display links'); + + return implode('
', $summary); + } + + /** + * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements(). + */ + public function viewElements(EntityInterface $entity, $langcode, array $items) { + // Remove un-accessible items. + parent::viewElements($entity, $langcode, $items); + + $view_mode = $this->getSetting('view_mode'); + $links = $this->getSetting('links'); + + $target_type = $this->field['settings']['target_type']; + + $elements = array(); + + foreach ($items as $delta => $item) { + // Protect ourselves from recursive rendering. + static $depth = 0; + $depth++; + if ($depth > 20) { + throw new 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']))); + } + + $entity = clone $item['entity']; + unset($entity->content); + $elements[$delta] = entity_view($entity, $view_mode, $langcode); + + if (empty($links) && isset($result[$delta][$target_type][$item['target_id']]['links'])) { + // Hide the element links. + $elements[$delta][$target_type][$item['target_id']]['links']['#access'] = FALSE; + } + $depth = 0; + } + + return $elements; + } +} diff --git a/core/modules/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..f6b5fac --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php @@ -0,0 +1,110 @@ + $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 (!isset($target_entities[$identifier])) { + // The entity no longer exists, so remove the key. + $rekey = TRUE; + unset($items[$id][$delta]); + continue; + } + + $items[$id][$delta]['entity'] = $target_entities[$identifier]; + + $entity = $target_entities[$identifier]; + + // @todo: Improve when we have entity_access(). + $entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE; + if (!$entity_access) { + continue; + } + + // Mark item as accessible. + $items[$id][$delta]['access'] = TRUE; + } + + 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::prepareView(). + */ + public function viewElements(EntityInterface $entity, $langcode, array $items) { + // Remove un-accessible items. + foreach ($items as $delta => $item) { + if (empty($item['access'])) { + unset($items[$delta]); + } + } + return array(); + } +} diff --git a/core/modules/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..148e64d --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php @@ -0,0 +1,42 @@ + $item) { + $elements[$delta] = array('#markup' => check_plain($item['target_id'])); + } + + return $elements; + } +} diff --git a/core/modules/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..efae069 --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php @@ -0,0 +1,80 @@ + t('Link label to the referenced entity'), + '#type' => 'checkbox', + '#default_value' => $this->getSetting('link'), + ); + + return $elements; + } + + /** + * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::settingsSummary(). + */ + public function settingsSummary() { + $summary = array(); + $summary[] = $this->getSetting('link') ? t('Link to the referenced entity') : t('No link'); + + return implode('
', $summary); + } + + /** + * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements(). + */ + public function viewElements(EntityInterface $entity, $langcode, array $items) { + // Remove un-accessible items. + parent::viewElements($entity, $langcode, $items); + + $elements = array(); + + foreach ($items as $delta => $item) { + $entity = $item['entity']; + $label = $entity->label(); + // If the link is to be displayed and the entity has a uri, + // display a link. + if ($this->getSetting('link') && $uri = $entity->uri()) { + $elements[$delta] = array('#markup' => l($label, $uri['path'], $uri['options'])); + } + else { + $elements[$delta] = array('#markup' => check_plain($label)); + } + } + + return $elements; + } +} diff --git a/core/modules/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..053f16a --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php @@ -0,0 +1,84 @@ +prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entity_reference/autocomplete/tags'); + } + + /** + * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate() + */ + public function elementValidate($element, &$form_state, $form) { + $value = array(); + // If a value was entered into the autocomplete. + $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..c0343bd --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php @@ -0,0 +1,91 @@ +prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entity_reference/autocomplete/single'); + return array('target_id' => $element); + } + + /** + * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate() + */ + public function elementValidate($element, &$form_state, $form) { + $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 + // popualte 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..f00a8c2 --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php @@ -0,0 +1,126 @@ + 'select', + '#title' => t('Autocomplete matching'), + '#default_value' => $this->getSetting('match_operator'), + '#options' => array( + 'STARTS_WITH' => t('Starts with'), + 'CONTAINS' => t('Contains'), + ), + '#description' => t('Select the method used to collect autocomplete suggestions. Note that Contains can cause performance issues on sites with thousands of nodes.'), + ); + $element['size'] = array( + '#type' => 'textfield', + '#title' => t('Size of textfield'), + '#default_value' => $this->getSetting('size'), + '#element_validate' => array('form_validate_number'), + // Minimum value for form_validate_number(). + '#min' => 1, + '#required' => TRUE, + ); + + return $element; + } + + /** + * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::formElement(). + */ + public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) { + $element = $this->prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entity_reference/autocomplete/single'); + return array('target_id' => $element); + } + + /** + * Prepares the element. + */ + protected function prepareElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state, $default_path) { + $instance = $this->instance; + $field = $this->field; + $entity = isset($element['#entity']) ? $element['#entity'] : NULL; + + // Prepare the autocomplete path. + $path = $this->getSetting('path'); + $autocomplete_path = !empty($path) ? $path : $default_path; + $autocomplete_path .= '/' . $field['field_name'] . '/' . $instance['entity_type'] . '/' . $instance['bundle'] . '/'; + + // Use as a placeholder in the URL when we don't have an entity. + // Most webservers collapse two consecutive slashes. + $id = 'NULL'; + if ($entity) { + if ($eid = $entity->id()) { + $id = $eid; + } + } + $autocomplete_path .= $id; + + $element += array( + '#type' => 'textfield', + '#maxlength' => 1024, + '#default_value' => implode(', ', $this->getLabels($items)), + '#autocomplete_path' => $autocomplete_path, + '#size' => $this->getSetting('size'), + '#element_validate' => array(array($this, 'elementValidate')), + ); + return $element; + } + + /** + * Overrides Drupal\field\Plugin\Type\Widget\WidgetBase::errorElement(). + */ + public function errorElement(array $element, array $error, array $form, array &$form_state) { + return $element['target_id']; + } + + /** + * Validates an element. + */ + public function elementValidate($element, &$form_state, $form) { } + + /** + * Gets the entity labels. + */ + protected function getLabels(array $items) { + $entity_ids = array(); + $entity_labels = array(); + + // Build an array of entities ID. + foreach ($items as $item) { + $entity_ids[] = $item['target_id']; + } + + // Load those entities and loop through them to extract their labels. + $entities = entity_load_multiple($this->field['settings']['target_type'], $entity_ids); + + foreach ($entities as $entity_id => $entity_item) { + $label = $entity_item->label(); + $key = "$label ($entity_id)"; + // Labels containing commas or quotes must be wrapped in quotes. + if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) { + $key = '"' . str_replace('"', '""', $key) . '"'; + } + $entity_labels[] = $key; + } + return $entity_labels; + } +} diff --git a/core/modules/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..4971653 --- /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..42ad62b --- /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..bcda1e6 --- /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..8834969 --- /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 diplayed. + $entity_type = 'node'; + $entity_info = entity_get_info($entity_type); + foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) { + $this->assertFieldByName('instance[settings][handler_settings][target_bundles][' . $bundle_name . ']'); + } + + // Test the sort settings. + $options = array('none', 'field'); + $this->assertFieldSelectOptions('instance[settings][handler_settings][sort][type]', $options); + // Option 0: no sort. + $this->assertFieldByName('instance[settings][handler_settings][sort][type]', 'none'); + $this->assertNoFieldByName('instance[settings][handler_settings][sort][property]'); + $this->assertNoFieldByName('instance[settings][handler_settings][sort][field]'); + $this->assertNoFieldByName('instance[settings][handler_settings][sort][direction]'); + // Option 1: sort by field. + $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][type]' => 'field'), 'instance[settings][handler_settings][sort][type]'); + $this->assertNoFieldByName('instance[settings][handler_settings][sort][property]'); + $this->assertFieldByName('instance[settings][handler_settings][sort][field]', ''); + $this->assertFieldByName('instance[settings][handler_settings][sort][direction]', 'ASC'); + // Set back to no sort. + $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][type]' => 'none'), 'instance[settings][handler_settings][sort][type]'); + + // Third step: confirm. + $this->drupalPost(NULL, array(), t('Save settings')); + + // Check that the field appears in the overview form. + $this->assertFieldByXPath('//table[@id="field-overview"]//td[1]', 'Test label', t('Field was created and appears in the overview page.')); + } +} diff --git a/core/modules/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..4fed11a --- /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/EntityReferenceItemTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceItemTest.php new file mode 100644 index 0000000..eda7f7d --- /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..21a4a46 --- /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 => $comment_labels['published_published'], + ), + ), + ), + array( + 'arguments' => array( + array('Published', 'CONTAINS'), + ), + 'result' => array( + 'comment_node_article' => array( + $comments['published_published']->cid => $comment_labels['published_published'], + ), + ), + ), + array( + 'arguments' => array( + array('invalid comment', 'CONTAINS'), + ), + 'result' => array(), + ), + array( + 'arguments' => array( + array('Comment Unpublished', 'CONTAINS'), + ), + 'result' => array(), + ), + ); + $this->assertReferencable($field, $instance, $referencable_tests, 'Comment handler'); + + // Test as a comment admin. + $admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments')); + $GLOBALS['user'] = $admin_user; + $referencable_tests = array( + array( + 'arguments' => array( + array(NULL, 'CONTAINS'), + ), + 'result' => array( + 'comment_node_article' => array( + $comments['published_published']->cid => $comment_labels['published_published'], + $comments['published_unpublished']->cid => $comment_labels['published_unpublished'], + ), + ), + ), + ); + $this->assertReferencable($field, $instance, $referencable_tests, 'Comment handler (comment admin)'); + + // Test as a node and comment admin. + $admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments', 'bypass node access')); + $GLOBALS['user'] = $admin_user; + $referencable_tests = array( + array( + 'arguments' => array( + array(NULL, 'CONTAINS'), + ), + 'result' => array( + 'comment_node_article' => array( + $comments['published_published']->cid => $comment_labels['published_published'], + $comments['published_unpublished']->cid => $comment_labels['published_unpublished'], + $comments['unpublished_published']->cid => $comment_labels['unpublished_published'], + ), + ), + ), + ); + $this->assertReferencable($field, $instance, $referencable_tests, 'Comment handler (comment + node admin)'); + } +} diff --git a/core/modules/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..7d48215 --- /dev/null +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php @@ -0,0 +1,152 @@ + '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( + 'type' => 'field', + 'field' => 'field_text.value', + 'direction' => 'DESC', + ), + ), + ), + ); + + // Build a set of test data. + $node_values = array( + 'published1' => array( + 'type' => 'article', + 'status' => 1, + 'title' => 'Node published1 (<&>)', + 'uid' => 1, + 'field_text' => array( + LANGUAGE_NOT_SPECIFIED => array( + array( + 'value' => 1, + ), + ), + ), + ), + 'published2' => array( + 'type' => 'article', + 'status' => 1, + 'title' => 'Node published2 (<&>)', + 'uid' => 1, + 'field_text' => array( + LANGUAGE_NOT_SPECIFIED => array( + array( + 'value' => 2, + ), + ), + ), + ), + ); + + $nodes = array(); + $node_labels = array(); + foreach ($node_values as $key => $values) { + $node = entity_create('node', $values); + $node->save(); + $nodes[$key] = $node; + $node_labels[$key] = check_plain($node->label()); + } + + // Test as a non-admin. + $normal_user = $this->drupalCreateUser(array('access content')); + $GLOBALS['user'] = $normal_user; + + $handler = entity_reference_get_selection_handler($field, $instance); + + // Not only assert the result, but make sure the keys are sorted as + // expected. + $result = $handler->getReferencableEntities(); + $expected_result = array( + $nodes['published2']->nid => $node_labels['published2'], + $nodes['published1']->nid => $node_labels['published1'], + ); + $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.'); + + // Assert sort by property. + $instance['settings']['handler_settings']['sort'] = array( + 'type' => 'field', + '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_ui/lib/Drupal/field_ui/Tests/FieldUiTestBase.php b/core/modules/field_ui/lib/Drupal/field_ui/Tests/FieldUiTestBase.php index aa923f1..2e7f36f 100644 --- a/core/modules/field_ui/lib/Drupal/field_ui/Tests/FieldUiTestBase.php +++ b/core/modules/field_ui/lib/Drupal/field_ui/Tests/FieldUiTestBase.php @@ -19,7 +19,7 @@ * * @var array */ - public static $modules = array('node', 'field_ui', 'field_test', 'taxonomy'); + public static $modules = array('node', 'field_ui', 'field_test', 'taxonomy', 'entity_reference'); function setUp() { parent::setUp(); diff --git a/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php b/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php index 7298c36..7553aa7 100644 --- a/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php +++ b/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php @@ -41,7 +41,10 @@ function setUp() { $field = array( 'field_name' => 'field_' . $vocabulary->id(), - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', + 'settings' => array( + 'target_type' => 'taxonomy_term', + ), ); field_create_field($field); @@ -397,7 +400,7 @@ function testDuplicateFieldName() { $edit = array( 'fields[_add_new_field][field_name]' => 'tags', 'fields[_add_new_field][label]' => $this->randomName(), - 'fields[_add_new_field][type]' => 'taxonomy_term_reference', + 'fields[_add_new_field][type]' => 'entity_reference', 'fields[_add_new_field][widget_type]' => 'options_select', ); $url = 'admin/structure/types/manage/' . $this->type . '/fields'; 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.info b/core/modules/forum/forum.info index 79317ea..a5428aa 100644 --- a/core/modules/forum/forum.info +++ b/core/modules/forum/forum.info @@ -3,6 +3,7 @@ description = Provides discussion forums. dependencies[] = node dependencies[] = history dependencies[] = taxonomy +dependencies[] = entity_reference dependencies[] = comment package = Core version = VERSION diff --git a/core/modules/forum/forum.install b/core/modules/forum/forum.install index b1e63de..e683b2a 100644 --- a/core/modules/forum/forum.install +++ b/core/modules/forum/forum.install @@ -58,14 +58,9 @@ function forum_enable() { if (!field_info_field('taxonomy_forums')) { $field = array( 'field_name' => 'taxonomy_forums', - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($field); @@ -90,19 +85,28 @@ function forum_enable() { 'widget' => array( 'type' => 'options_select', ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $vocabulary->id(), + ), + 'auto_create' => TRUE, + ), + ), ); field_create_instance($instance); // Assign display settings for the 'default' and 'teaser' view modes. entity_get_display('node', 'forum', 'default') ->setComponent('taxonomy_forums', array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); entity_get_display('node', 'forum', 'teaser') ->setComponent('taxonomy_forums', array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); 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/node/lib/Drupal/node/Plugin/views/wizard/Node.php b/core/modules/node/lib/Drupal/node/Plugin/views/wizard/Node.php index fec2bfe..1101a94 100644 --- a/core/modules/node/lib/Drupal/node/Plugin/views/wizard/Node.php +++ b/core/modules/node/lib/Drupal/node/Plugin/views/wizard/Node.php @@ -281,7 +281,7 @@ protected function build_filters(&$form, &$form_state) { foreach (field_info_instances($this->entity_type, $bundle) as $instance) { // We define "tag-like" taxonomy fields as ones that use the // "Autocomplete term widget (tagging)" widget. - if ($instance['widget']['type'] == 'taxonomy_autocomplete') { + if ($instance['widget']['type'] == 'entity_reference_autocomplete_tags') { $tag_fields[] = $instance['field_name']; } } @@ -308,6 +308,7 @@ protected function build_filters(&$form, &$form_state) { '#size' => 30, '#maxlength' => 1024, '#field_name' => $tag_field_name, + // @todo: Replace? '#element_validate' => array('views_ui_taxonomy_autocomplete_validate'), ); } diff --git a/core/modules/options/options.module b/core/modules/options/options.module index d818966..e743333 100644 --- a/core/modules/options/options.module +++ b/core/modules/options/options.module @@ -445,14 +445,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 264a090..fe73210 100644 --- a/core/modules/rdf/rdf.module +++ b/core/modules/rdf/rdf.module @@ -789,7 +789,7 @@ function rdf_field_attach_view_alter(&$output, $context) { // Append term mappings on displayed taxonomy links. foreach (element_children($output) as $field_name) { $element = &$output[$field_name]; - if ($element['#field_type'] == 'taxonomy_term_reference' && $element['#formatter'] == 'taxonomy_term_reference_link') { + if ($element['#field_type'] == 'entity_reference' && $element['#formatter'] == 'entity_reference_label') { foreach ($element['#items'] as $delta => $item) { // This function is invoked during entity preview when taxonomy term // reference items might contain free-tagging terms that do not exist 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 3dd810c..60967a8 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() { // 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_test', 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. @@ -83,26 +83,26 @@ public function testReadWrite() { $this->assertTrue($entity->user_id instanceof FieldInterface, 'Field implements interface'); $this->assertTrue($entity->user_id[0] instanceof FieldItemInterface, 'Field item implements interface'); - $this->assertEqual($this->entity_user->uid, $entity->user_id->value, 'User id can be read.'); + $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, 'User id can be read.'); $this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, 'User name can be read.'); // 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, 'Updated user id can be read.'); + $this->assertEqual($new_user->uid, $entity->user_id->target_id, 'Updated user id can be read.'); $this->assertEqual($new_user->name, $entity->user_id->entity->name, 'Updated user name value can be read.'); // 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, 'Updated user id can be read.'); + $entity->user_id->target_id = $new_user->uid; + $this->assertEqual($new_user->uid, $entity->user_id->target_id, 'Updated user id can be read.'); $this->assertEqual($new_user->name, $entity->user_id->entity->name, 'Updated user name value can be read.'); // Try unsetting a field. $entity->name->value = NULL; - $entity->user_id->value = NULL; + $entity->user_id->target_id = NULL; $this->assertNull($entity->name->value, 'Name field is not set.'); - $this->assertNull($entity->user_id->value, 'User ID field is not set.'); + $this->assertNull($entity->user_id->target_id, 'User ID field is not set.'); $this->assertNull($entity->user_id->entity, 'User entity field is not set.'); // Test using isset(), empty() and unset(). @@ -167,7 +167,7 @@ public function testReadWrite() { $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; @@ -177,7 +177,7 @@ public function testReadWrite() { 'field_test_text' => $text_item, )); $this->assertEqual($this->entity_name, $entity->name->value, 'Name value can be read.'); - $this->assertEqual($this->entity_user->uid, $entity->user_id->value, 'User id can be read.'); + $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, 'User id can be read.'); $this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, 'User name can be read.'); $this->assertEqual($this->entity_field_text, $entity->field_test_text->value, 'Text field can be read.'); @@ -189,7 +189,7 @@ public function testReadWrite() { $this->assertTrue($entity->name !== $entity2->name, 'Copying properties results in a different field object.'); $this->assertEqual($entity->name->value, $entity2->name->value, 'Name field copied.'); - $this->assertEqual($entity->user_id->value, $entity2->user_id->value, 'User id field copied.'); + $this->assertEqual($entity->user_id->target_id, $entity2->user_id->target_id, 'User id field copied.'); $this->assertEqual($entity->field_test_text->value, $entity2->field_test_text->value, 'Text field copied.'); // Tests adding a value to a field item list. @@ -238,14 +238,14 @@ public function testReadWrite() { $this->assertEqual($entity->name->value, 'foo', 'Field value has been set via setPropertyValue() on an entity.'); // 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_test', array( 'name' => $name_item, 'user_id' => $user_item, 'field_test_text' => $text_item, )); - $this->assertNotNull($entity->user_id->value, 'User id is not NULL'); - $this->assertIdentical($entity->user_id->value, 0, 'User id has been set to 0'); + $this->assertNotNull($entity->user_id->target_id, 'User id is not NULL'); + $this->assertIdentical($entity->user_id->target_id, 0, 'User id has been set to 0'); // Test setting the ID with the value only. $entity = entity_create('entity_test', array( @@ -253,8 +253,8 @@ public function testReadWrite() { 'user_id' => 0, 'field_test_text' => $text_item, )); - $this->assertNotNull($entity->user_id->value, 'User id is not NULL'); - $this->assertIdentical($entity->user_id->value, 0, 'User id has been set to 0'); + $this->assertNotNull($entity->user_id->target_id, 'User id is not NULL'); + $this->assertIdentical($entity->user_id->target_id, 0, 'User id has been set to 0'); } /** @@ -273,7 +273,7 @@ public function testSave() { $this->assertTrue(is_string($entity->uuid->value), 'UUID value can be read.'); $this->assertEqual(LANGUAGE_NOT_SPECIFIED, $entity->langcode->value, 'Language code can be read.'); $this->assertEqual(language_load(LANGUAGE_NOT_SPECIFIED), $entity->langcode->language, 'Language object can be read.'); - $this->assertEqual($this->entity_user->uid, $entity->user_id->value, 'User id can be read.'); + $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, 'User id can be read.'); $this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, 'User name can be read.'); $this->assertEqual($this->entity_field_text, $entity->field_test_text->value, 'Text field can be read.'); } @@ -293,7 +293,7 @@ public function testIntrospection() { $wrapped_entity = typed_data()->create($definition); $definitions = $wrapped_entity->getPropertyDefinitions($definition); $this->assertEqual($definitions['name']['type'], 'string_field', 'Name field found.'); - $this->assertEqual($definitions['user_id']['type'], 'entityreference_field', 'User field found.'); + $this->assertEqual($definitions['user_id']['type'], 'entity_reference_field', 'User field found.'); $this->assertEqual($definitions['field_test_text']['type'], 'text_field', 'Test-text-field field found.'); // Test introspecting an entity object. @@ -302,14 +302,14 @@ public function testIntrospection() { $definitions = $entity->getPropertyDefinitions(); $this->assertEqual($definitions['name']['type'], 'string_field', 'Name field found.'); - $this->assertEqual($definitions['user_id']['type'], 'entityreference_field', 'User field found.'); + $this->assertEqual($definitions['user_id']['type'], 'entity_reference_field', 'User field found.'); $this->assertEqual($definitions['field_test_text']['type'], 'text_field', 'Test-text-field field found.'); $name_properties = $entity->name->getPropertyDefinitions(); $this->assertEqual($name_properties['value']['type'], 'string', 'String value property of the name found.'); $userref_properties = $entity->user_id->getPropertyDefinitions(); - $this->assertEqual($userref_properties['value']['type'], 'integer', 'Entity id property of the user found.'); + $this->assertEqual($userref_properties['target_id']['type'], 'integer', 'Entity id property of the user found.'); $this->assertEqual($userref_properties['entity']['type'], 'entity', '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..f39a0b4 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php @@ -81,16 +81,29 @@ protected function setUp() { $this->fieldName = strtolower($this->randomName()); $field = array( 'field_name' => $this->fieldName, - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', + 'settings' => array( + 'target_type' => 'taxonomy_term', + ), ); - $field['settings']['allowed_values']['vocabulary'] = $vocabulary->id(); + field_create_field($field); // Third, create the instance. $instance = array( 'entity_type' => 'entity_test', 'field_name' => $this->fieldName, 'bundle' => 'entity_test', + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $vocabulary->id(), + ), + 'auto_create' => TRUE, + ), + ), ); + field_create_instance($instance); // Create two terms and also two accounts. for ($i = 0; $i <= 1; $i++) { @@ -109,7 +122,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 370622d..35995f7 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php @@ -186,13 +186,13 @@ function testMultilingualProperties() { $entity = entity_test_load($entity->id()); $this->assertEqual($entity->language()->langcode, LANGUAGE_NOT_SPECIFIED, 'Entity created as language neutral.'); $this->assertEqual($name, $entity->getTranslation(LANGUAGE_DEFAULT)->get('name')->value, 'The entity name has been correctly stored as language neutral.'); - $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_DEFAULT)->get('user_id')->value, 'The entity author has been correctly stored as language neutral.'); + $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_DEFAULT)->get('user_id')->target_id, 'The entity author has been correctly stored as language neutral.'); // 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, 'The entity name defaults to neutral language.'); - $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->value, 'The entity author defaults to neutral language.'); + $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->target_id, 'The entity author defaults to neutral language.'); $this->assertEqual($name, $entity->get('name')->value, 'The entity name can be retrieved without specifying a language.'); - $this->assertEqual($uid, $entity->get('user_id')->value, 'The entity author can be retrieved without specifying a language.'); + $this->assertEqual($uid, $entity->get('user_id')->target_id, 'The entity author can be retrieved without specifying a language.'); // Create a language-aware entity and check that properties are stored // as language-aware. @@ -201,13 +201,13 @@ function testMultilingualProperties() { $entity = entity_test_load($entity->id()); $this->assertEqual($entity->language()->langcode, $langcode, 'Entity created as language specific.'); $this->assertEqual($name, $entity->getTranslation($langcode)->get('name')->value, 'The entity name has been correctly stored as a language-aware property.'); - $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->value, 'The entity author has been correctly stored as a language-aware property.'); + $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->target_id, 'The entity author has been correctly stored as a language-aware property.'); // 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, 'The entity name defaults to the default language.'); - $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('user_id')->value, 'The entity author defaults to the default language.'); + $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('user_id')->target_id, 'The entity author defaults to the default language.'); $this->assertEqual($name, $entity->get('name')->value, 'The entity name can be retrieved without specifying a language.'); - $this->assertEqual($uid, $entity->get('user_id')->value, 'The entity author can be retrieved without specifying a language.'); + $this->assertEqual($uid, $entity->get('user_id')->target_id, 'The entity author can be retrieved without specifying a language.'); // Create property translations. $properties = array(); @@ -234,7 +234,7 @@ function testMultilingualProperties() { foreach ($this->langcodes as $langcode) { $args = array('%langcode' => $langcode); $this->assertEqual($properties[$langcode]['name'][0], $entity->getTranslation($langcode)->get('name')->value, format_string('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('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('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 cb2f7f3..88a2509 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php @@ -81,7 +81,7 @@ function testCRUD() { $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 f34cd9d..cc61e80 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php @@ -90,7 +90,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 6dd33b1..92bdd44 100644 --- a/core/modules/system/system.module +++ b/core/modules/system/system.module @@ -2134,7 +2134,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 a65f06f..561821c 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/EntityTestStorageController.php b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php index e3b45fa..b76340f 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 @@ -80,7 +80,7 @@ protected function attachPropertyData(&$queried_entities, $load_revision = FALSE $langcode = empty($values['default_langcode']) ? $values['langcode'] : LANGUAGE_DEFAULT; $queried_entities[$id]->name[$langcode][0]['value'] = $values['name']; - $queried_entities[$id]->user_id[$langcode][0]['value'] = $values['user_id']; + $queried_entities[$id]->user_id[$langcode][0]['target_id'] = $values['user_id']; } } @@ -108,7 +108,7 @@ protected function postSave(EntityInterface $entity, $update) { 'langcode' => $langcode, 'default_langcode' => intval($default_langcode == $langcode), 'name' => $translation->name->value, - 'user_id' => $translation->user_id->value, + 'user_id' => $translation->user_id->target_id, ); $query @@ -168,8 +168,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/widget/TaxonomyAutocompleteWidget.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/widget/TaxonomyAutocompleteWidget.php deleted file mode 100644 index 0d5dfd4..0000000 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/widget/TaxonomyAutocompleteWidget.php +++ /dev/null @@ -1,107 +0,0 @@ - '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) { - $field = $this->field; - - $tags = array(); - foreach ($items as $item) { - $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']); - } - $element += array( - '#type' => 'textfield', - '#default_value' => taxonomy_implode_tags($tags), - '#autocomplete_path' => $this->getSetting('autocomplete_path') . '/' . $field['field_name'], - '#size' => $this->getSetting('size'), - '#placeholder' => $this->getSetting('placeholder'), - '#maxlength' => 1024, - '#element_validate' => array('taxonomy_autocomplete_validate'), - ); - - return $element; - } - - /** - * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::massageFormValues() - */ - public function massageFormValues(array $values, array $form, array &$form_state) { - // Autocomplete widgets do not send their tids in the form, so we must detect - // them here and process them independently. - $terms = array(); - $field = $this->field; - - // Collect candidate vocabularies. - foreach ($field['settings']['allowed_values'] as $tree) { - if ($vocabulary = entity_load('taxonomy_vocabulary', $tree['vocabulary'])) { - $vocabularies[$vocabulary->id()] = $vocabulary; - } - } - - // Translate term names into actual terms. - foreach($values as $value) { - // See if the term exists in the chosen vocabulary and return the tid; - // otherwise, create a new 'autocreate' term for insert/update. - if ($possibilities = entity_load_multiple_by_properties('taxonomy_term', array('name' => trim($value), 'vid' => array_keys($vocabularies)))) { - $term = array_pop($possibilities); - } - else { - $vocabulary = reset($vocabularies); - $term = array( - 'tid' => 'autocreate', - 'vid' => $vocabulary->id(), - 'name' => $value, - ); - } - $terms[] = (array)$term; - } - - return $terms; - } - -} diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/argument_default/Tid.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/argument_default/Tid.php index b09ed5a..e3e8c15 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/argument_default/Tid.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/argument_default/Tid.php @@ -138,7 +138,7 @@ function get_argument() { $fields = field_info_instances('node', $node->type); foreach ($fields as $name => $info) { $field_info = field_info_field($name); - if ($field_info['type'] == 'taxonomy_term_reference') { + if ($field_info['type'] == 'entity_reference') { $items = field_get_items('node', $node, $name); if (is_array($items)) { foreach ($items as $item) { diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/RssTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/RssTest.php index 278db90..ac63ef8 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/RssTest.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/RssTest.php @@ -36,15 +36,10 @@ function setUp() { $field = array( 'field_name' => 'taxonomy_' . $this->vocabulary->id(), - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($field); @@ -56,11 +51,20 @@ function setUp() { '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('taxonomy_' . $this->vocabulary->id(), array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); } @@ -84,7 +88,7 @@ function testTaxonomyRss() { // Change the format to 'RSS category'. $this->drupalGet("admin/structure/types/manage/article/display/rss"); $edit = array( - "fields[taxonomy_" . $this->vocabulary->id() . "][type]" => 'taxonomy_term_reference_rss_category', + "fields[taxonomy_" . $this->vocabulary->id() . "][type]" => 'entity_reference_rss_category', ); $this->drupalPost(NULL, $edit, t('Save')); diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TaxonomyTermReferenceItemTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TaxonomyTermReferenceItemTest.php deleted file mode 100644 index 99258bc..0000000 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TaxonomyTermReferenceItemTest.php +++ /dev/null @@ -1,114 +0,0 @@ - 'Taxonomy reference API', - 'description' => 'Tests using entity fields of the taxonomy term reference field type.', - 'group' => 'Taxonomy', - ); - } - - public function setUp() { - parent::setUp(); - $vocabulary = entity_create('taxonomy_vocabulary', array( - 'name' => $this->randomName(), - 'vid' => drupal_strtolower($this->randomName()), - 'langcode' => LANGUAGE_NOT_SPECIFIED, - )); - $vocabulary->save(); - $field = array( - 'field_name' => 'field_test_taxonomy', - 'type' => 'taxonomy_term_reference', - 'cardinality' => FIELD_CARDINALITY_UNLIMITED, - 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $vocabulary->id(), - 'parent' => 0, - ), - ), - ), - ); - field_create_field($field); - $instance = array( - 'entity_type' => 'entity_test', - 'field_name' => 'field_test_taxonomy', - 'bundle' => 'entity_test', - 'widget' => array( - 'type' => 'options_select', - ), - ); - field_create_instance($instance); - $this->term = entity_create('taxonomy_term', array( - 'name' => $this->randomName(), - 'vid' => $vocabulary->id(), - 'langcode' => LANGUAGE_NOT_SPECIFIED, - )); - $this->term->save(); - } - - /** - * Tests using entity fields of the taxonomy term reference field type. - */ - public function testTaxonomyTermReferenceItem() { - $tid = $this->term->id(); - // Just being able to create the entity like this verifies a lot of code. - $entity = entity_create('entity_test', array()); - $entity->field_test_taxonomy->tid = $this->term->tid; - $entity->name->value = $this->randomName(); - $entity->save(); - - $entity = entity_load('entity_test', $entity->id()); - $this->assertTrue($entity->field_test_taxonomy instanceof FieldInterface, 'Field implements interface.'); - $this->assertTrue($entity->field_test_taxonomy[0] instanceof FieldItemInterface, 'Field item implements interface.'); - $this->assertEqual($entity->field_test_taxonomy->tid, $this->term->tid); - $this->assertEqual($entity->field_test_taxonomy->entity->name, $this->term->name); - $this->assertEqual($entity->field_test_taxonomy->entity->id(), $tid); - $this->assertEqual($entity->field_test_taxonomy->entity->uuid(), $this->term->uuid()); - - // Change the name of the term via the reference. - $new_name = $this->randomName(); - $entity->field_test_taxonomy->entity->name = $new_name; - $entity->field_test_taxonomy->entity->save(); - // Verify it is the correct name. - $term = entity_load('taxonomy_term', $tid); - $this->assertEqual($term->name, $new_name); - - // Make sure the computed term reflects updates to the term id. - $term2 = entity_create('taxonomy_term', array( - 'name' => $this->randomName(), - 'vid' => $this->term->vid, - 'langcode' => LANGUAGE_NOT_SPECIFIED, - )); - $term2->save(); - - $entity->field_test_taxonomy->tid = $term2->tid; - $this->assertEqual($entity->field_test_taxonomy->entity->id(), $term2->tid); - $this->assertEqual($entity->field_test_taxonomy->entity->name, $term2->name); - } - -} diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldMultipleVocabularyTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldMultipleVocabularyTest.php index 25bcc07..20e2dd3 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldMultipleVocabularyTest.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldMultipleVocabularyTest.php @@ -43,20 +43,11 @@ function setUp() { $this->field_name = drupal_strtolower($this->randomName()); $this->field = array( 'field_name' => $this->field_name, - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary1->id(), - 'parent' => '0', - ), - array( - 'vocabulary' => $this->vocabulary2->id(), - 'parent' => '0', - ), - ), - ) + 'target_type' => 'taxonomy_term', + ), ); field_create_field($this->field); $this->instance = array( @@ -66,11 +57,21 @@ function setUp() { 'widget' => array( 'type' => 'options_select', ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $this->vocabulary1->id(), + $this->vocabulary2->id(), + ), + 'auto_create' => TRUE, + ), + ), ); field_create_instance($this->instance); entity_get_display('test_entity', 'test_bundle', 'full') ->setComponent($this->field_name, array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); } diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldTest.php index c20acf7..038f48c 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldTest.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermFieldTest.php @@ -43,15 +43,10 @@ function setUp() { $this->field_name = drupal_strtolower($this->randomName()); $this->field = array( 'field_name' => $this->field_name, - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => '0', - ), - ), - ) + 'target_type' => 'taxonomy_term', + ), ); field_create_field($this->field); $this->instance = array( @@ -61,11 +56,20 @@ function setUp() { '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('test_entity', 'test_bundle', 'full') ->setComponent($this->field_name, array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); } diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermIndexTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermIndexTest.php index f9cba0d..9c53df0 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermIndexTest.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermIndexTest.php @@ -33,15 +33,10 @@ function setUp() { $this->field_name_1 = drupal_strtolower($this->randomName()); $this->field_1 = array( 'field_name' => $this->field_name_1, - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($this->field_1); @@ -52,26 +47,30 @@ function setUp() { '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_1); entity_get_display('node', 'article', 'default') ->setComponent($this->field_name_1, array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); $this->field_name_2 = drupal_strtolower($this->randomName()); $this->field_2 = array( 'field_name' => $this->field_name_2, - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($this->field_2); @@ -82,11 +81,20 @@ function setUp() { '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_2); entity_get_display('node', 'article', 'default') ->setComponent($this->field_name_2, array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); } diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermTest.php index 93cc8d4..ab5ee0b 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermTest.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermTest.php @@ -28,15 +28,10 @@ function setUp() { $field = array( 'field_name' => 'taxonomy_' . $this->vocabulary->id(), - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($field); @@ -48,11 +43,20 @@ function setUp() { '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' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); } @@ -143,7 +147,7 @@ function testNodeTermCreationAndDeletion() { // Enable tags in the vocabulary. $instance = $this->instance; $instance['widget'] = array( - 'type' => 'taxonomy_autocomplete', + 'type' => 'entity_reference_autocomplete_tags', 'settings' => array( 'placeholder' => 'Start typing here.', ), @@ -506,7 +510,7 @@ function testTaxonomyGetTermByName() { function testReSavingTags() { // Enable tags in the vocabulary. $instance = $this->instance; - $instance['widget'] = array('type' => 'taxonomy_autocomplete'); + $instance['widget'] = array('type' => 'entity_reference_autocomplete_tags'); field_update_instance($instance); // Create a term and a node using it. diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TokenReplaceTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TokenReplaceTest.php index ea73152..b15085d 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TokenReplaceTest.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TokenReplaceTest.php @@ -29,15 +29,10 @@ function setUp() { $field = array( 'field_name' => 'taxonomy_' . $this->vocabulary->id(), - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($field); @@ -49,11 +44,20 @@ function setUp() { '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('taxonomy_' . $this->vocabulary->id(), array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); } diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/Views/TaxonomyTestBase.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/Views/TaxonomyTestBase.php index 67adc3a..a34796d 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/Views/TaxonomyTestBase.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/Views/TaxonomyTestBase.php @@ -82,16 +82,11 @@ protected function mockStandardInstall() { $this->vocabulary->save(); $field = array( 'field_name' => 'field_' . $this->vocabulary->id(), - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', // Set cardinality to unlimited for tagging. 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($field); @@ -101,21 +96,30 @@ protected function mockStandardInstall() { 'label' => 'Tags', 'bundle' => 'article', 'widget' => array( - 'type' => 'taxonomy_autocomplete', + 'type' => 'entity_reference_autocomplete_tags', 'weight' => -4, ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $this->vocabulary->id(), + ), + 'auto_create' => TRUE, + ), + ), ); field_create_instance($instance); entity_get_display('node', 'article', 'default') ->setComponent($instance['field_name'], array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); entity_get_display('node', 'article', 'teaser') ->setComponent($instance['field_name'], array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Type/TaxonomyTermReferenceItem.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Type/TaxonomyTermReferenceItem.php index 8eabe7d..678df5f 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Type/TaxonomyTermReferenceItem.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Type/TaxonomyTermReferenceItem.php @@ -10,7 +10,7 @@ use Drupal\Core\Entity\Field\FieldItemBase; /** - * Defines the 'taxonomy_term_reference' entity field item. + * Defines the 'entity_reference' entity field item. */ class TaxonomyTermReferenceItem extends FieldItemBase { diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/VocabularyStorageController.php b/core/modules/taxonomy/lib/Drupal/taxonomy/VocabularyStorageController.php index 3d2853d..a9a50a7 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/VocabularyStorageController.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/VocabularyStorageController.php @@ -28,7 +28,7 @@ protected function postSave(EntityInterface $entity, $update) { $fields = field_read_fields(); foreach ($fields as $field_name => $field) { $update_field = FALSE; - if ($field['type'] == 'taxonomy_term_reference') { + if ($field['type'] == 'entity_reference') { foreach ($field['settings']['allowed_values'] as $key => &$value) { if ($value['vocabulary'] == $entity->getOriginalID()) { $value['vocabulary'] = $entity->id(); diff --git a/core/modules/taxonomy/taxonomy.module b/core/modules/taxonomy/taxonomy.module index b82d3aa..521143f 100644 --- a/core/modules/taxonomy/taxonomy.module +++ b/core/modules/taxonomy/taxonomy.module @@ -26,14 +26,6 @@ const TAXONOMY_HIERARCHY_MULTIPLE = 2; /** - * Users can create new terms in a free-tagging vocabulary when - * submitting a taxonomy_autocomplete_widget. We store a term object - * whose tid is 'autocreate' as a field data item during widget - * validation and then actually create the term if/when that field - * data item makes it to taxonomy_field_insert/update(). - */ - -/** * Implements hook_help(). */ function taxonomy_help($path, $arg) { @@ -308,14 +300,6 @@ function taxonomy_menu() { 'type' => MENU_CALLBACK, 'file' => 'taxonomy.pages.inc', ); - $items['taxonomy/autocomplete/%'] = array( - 'title' => 'Autocomplete taxonomy', - 'page callback' => 'taxonomy_autocomplete', - 'page arguments' => array(2), - 'access arguments' => array('access content'), - 'type' => MENU_CALLBACK, - 'file' => 'taxonomy.pages.inc', - ); $items['admin/structure/taxonomy/%taxonomy_vocabulary'] = array( 'title callback' => 'entity_page_label', @@ -971,276 +955,15 @@ function taxonomy_implode_tags($tags, $vid = NULL) { /** * Implements hook_field_info(). * - * Field settings: - * - allowed_values: a list array of one or more vocabulary trees: - * - vocabulary: a vocabulary machine name. + * @todo: How do we maintain this in entity reference? * - parent: a term ID of a term whose children are allowed. This should be * '0' if all terms in a vocabulary are allowed. The allowed values do not * include the parent term. * */ function taxonomy_field_info() { - return array( - 'taxonomy_term_reference' => array( - 'label' => t('Term reference'), - 'description' => t('This field stores a reference to a taxonomy term.'), - 'default_widget' => 'options_select', - 'default_formatter' => 'taxonomy_term_reference_link', - 'field item class' => 'Drupal\taxonomy\Type\TaxonomyTermReferenceItem', - 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => '', - 'parent' => '0', - ), - ), - ), - ), - ); -} - -/** - * Implements hook_field_widget_info_alter(). - */ -function taxonomy_field_widget_info_alter(&$info) { - $info['options_select']['field_types'][] = 'taxonomy_term_reference'; - $info['options_buttons']['field_types'][] = 'taxonomy_term_reference'; -} - -/** - * Implements hook_options_list(). - */ -function taxonomy_options_list($field, $instance, $entity_type, $entity) { - $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values'; - return $function($field, $instance, $entity_type, $entity); -} - -/** - * Implements hook_field_validate(). - * - * Taxonomy field settings allow for either a single vocabulary ID, multiple - * vocabulary IDs, or sub-trees of a vocabulary to be specified as allowed - * values, although only the first of these is supported via the field UI. - * Confirm that terms entered as values meet at least one of these conditions. - * - * Possible error codes: - * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values. - */ -function taxonomy_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) { - // Build an array of existing term IDs so they can be loaded with - // taxonomy_term_load_multiple(); - foreach ($items as $delta => $item) { - if (!empty($item['tid']) && $item['tid'] != 'autocreate') { - $tids[] = $item['tid']; - } - } - if (!empty($tids)) { - $terms = taxonomy_term_load_multiple($tids); - - // Check each existing item to ensure it can be found in the - // allowed values for this field. - foreach ($items as $delta => $item) { - $validate = TRUE; - if (!empty($item['tid']) && $item['tid'] != 'autocreate') { - $validate = FALSE; - foreach ($field['settings']['allowed_values'] as $settings) { - // If no parent is specified, check if the term is in the vocabulary. - if (isset($settings['vocabulary']) && empty($settings['parent'])) { - if ($settings['vocabulary'] == $terms[$item['tid']]->bundle()) { - $validate = TRUE; - break; - } - } - // If a parent is specified, then to validate it must appear in the - // array returned by taxonomy_term_load_parents_all(). - elseif (!empty($settings['parent'])) { - $ancestors = taxonomy_term_load_parents_all($item['tid']); - foreach ($ancestors as $ancestor) { - if ($ancestor->tid == $settings['parent']) { - $validate = TRUE; - break 2; - } - } - } - } - } - if (!$validate) { - $errors[$field['field_name']][$langcode][$delta][] = array( - 'error' => 'taxonomy_term_reference_illegal_value', - 'message' => t('%name: illegal value.', array('%name' => $instance['label'])), - ); - } - } - } } -/** - * Implements hook_field_is_empty(). - */ -function taxonomy_field_is_empty($item, $field) { - if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) { - return TRUE; - } - return FALSE; -} - -/** - * Implements hook_field_formatter_info(). - */ -function taxonomy_field_formatter_info() { - return array( - 'taxonomy_term_reference_link' => array( - 'label' => t('Link'), - 'field types' => array('taxonomy_term_reference'), - ), - 'taxonomy_term_reference_plain' => array( - 'label' => t('Plain text'), - 'field types' => array('taxonomy_term_reference'), - ), - 'taxonomy_term_reference_rss_category' => array( - 'label' => t('RSS category'), - 'field types' => array('taxonomy_term_reference'), - ), - ); -} - -/** - * Implements hook_field_formatter_view(). - */ -function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) { - $element = array(); - - // Terms whose tid is 'autocreate' do not exist - // yet and $item['taxonomy_term'] is not set. Theme such terms as - // just their name. - - switch ($display['type']) { - case 'taxonomy_term_reference_link': - foreach ($items as $delta => $item) { - if ($item['tid'] == 'autocreate') { - $element[$delta] = array( - '#markup' => check_plain($item['name']), - ); - } - else { - $term = $item['taxonomy_term']; - $uri = $term->uri(); - $element[$delta] = array( - '#type' => 'link', - '#title' => $term->label(), - '#href' => $uri['path'], - '#options' => $uri['options'], - ); - } - } - break; - - case 'taxonomy_term_reference_plain': - foreach ($items as $delta => $item) { - $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->label() : $item['name']); - $element[$delta] = array( - '#markup' => check_plain($name), - ); - } - break; - - case 'taxonomy_term_reference_rss_category': - foreach ($items as $delta => $item) { - $entity->rss_elements[] = array( - 'key' => 'category', - 'value' => $item['tid'] != 'autocreate' ? $item['taxonomy_term']->label() : $item['name'], - 'attributes' => array( - 'domain' => $item['tid'] != 'autocreate' ? url('taxonomy/term/' . $item['tid'], array('absolute' => TRUE)) : '', - ), - ); - } - break; - } - - return $element; -} - -/** - * Returns the set of valid terms for a taxonomy field. - * - * @param $field - * The field definition. - * @param $instance - * The instance definition. It is recommended to only use instance level - * properties to filter out values from a list defined by field level - * properties. - * @param $entity_type - * The entity type the field is attached to. - * @param $entity - * The entity object the field is attached to, or NULL if no entity - * exists (e.g. in field settings page). - * - * @return - * The array of valid terms for this field, keyed by term id. - */ -function taxonomy_allowed_values($field, $instance, $entity_type, $entity) { - $options = array(); - foreach ($field['settings']['allowed_values'] as $tree) { - if ($vocabulary = taxonomy_vocabulary_load($tree['vocabulary'])) { - if ($terms = taxonomy_get_tree($vocabulary->id(), $tree['parent'], NULL, TRUE)) { - foreach ($terms as $term) { - $options[$term->tid] = str_repeat('-', $term->depth) . $term->label(); - } - } - } - } - return $options; -} - -/** - * Implements hook_field_formatter_prepare_view(). - * - * This preloads all taxonomy terms for multiple loaded objects at once and - * unsets values for invalid terms that do not exist. - */ -function taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) { - $tids = array(); - - // Collect every possible term attached to any of the fieldable entities. - foreach ($entities as $id => $entity) { - foreach ($items[$id] as $delta => $item) { - // Force the array key to prevent duplicates. - if ($item['tid'] != 'autocreate') { - $tids[$item['tid']] = $item['tid']; - } - } - } - if ($tids) { - $terms = taxonomy_term_load_multiple($tids); - - // Iterate through the fieldable entities again to attach the loaded term data. - foreach ($entities as $id => $entity) { - $rekey = FALSE; - - foreach ($items[$id] as $delta => $item) { - // Check whether the taxonomy term field instance value could be loaded. - if (isset($terms[$item['tid']])) { - // Replace the instance value with the term data. - $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']]; - } - // Terms to be created are not in $terms, but are still legitimate. - elseif ($item['tid'] == 'autocreate') { - // Leave the item in place. - } - // Otherwise, unset the instance value, since the term does not exist. - else { - unset($items[$id][$delta]); - $rekey = TRUE; - } - } - - if ($rekey) { - // Rekey the items array. - $items[$id] = array_values($items[$id]); - } - } - } -} /** * Title callback for term pages. @@ -1256,52 +979,6 @@ function taxonomy_term_title(Term $term) { } /** - * Form element validate handler for taxonomy term autocomplete element. - */ -function taxonomy_autocomplete_validate($element, &$form_state) { - // Split the values into an array. - // @see Drupal\taxonomy\Plugin\field\widget\TaxonomyAutocompleteWidget:massageFormValues() - $typed_terms = array(); - if ($tags = $element['#value']) { - $typed_terms = drupal_explode_tags($tags); - } - form_set_value($element, $typed_terms, $form_state); -} - -/** - * Implements hook_field_settings_form(). - */ -function taxonomy_field_settings_form($field, $instance, $has_data) { - // Get proper values for 'allowed_values_function', which is a core setting. - $vocabularies = taxonomy_vocabulary_load_multiple(); - $options = array(); - foreach ($vocabularies as $vocabulary) { - $options[$vocabulary->id()] = $vocabulary->name; - } - $form['allowed_values'] = array( - '#tree' => TRUE, - ); - - foreach ($field['settings']['allowed_values'] as $delta => $tree) { - $form['allowed_values'][$delta]['vocabulary'] = array( - '#type' => 'select', - '#title' => t('Vocabulary'), - '#default_value' => $tree['vocabulary'], - '#options' => $options, - '#required' => TRUE, - '#description' => t('The vocabulary which supplies the options for this field.'), - '#disabled' => $has_data, - ); - $form['allowed_values'][$delta]['parent'] = array( - '#type' => 'value', - '#value' => $tree['parent'], - ); - } - - return $form; -} - -/** * Implements hook_rdf_mapping(). * * @return array @@ -1365,23 +1042,6 @@ function taxonomy_rdf_mapping() { */ /** - * Implements hook_field_presave(). - * - * Create any new terms defined in a freetagging vocabulary. - */ -function taxonomy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) { - foreach ($items as $delta => $item) { - if ($item['tid'] == 'autocreate') { - unset($item['tid']); - $term = entity_create('taxonomy_term', $item); - $term->langcode = $langcode; - taxonomy_term_save($term); - $items[$delta]['tid'] = $term->tid; - } - } -} - -/** * Implements hook_node_insert(). */ function taxonomy_node_insert(Node $node) { @@ -1421,7 +1081,7 @@ function taxonomy_build_node_index($node) { foreach (field_info_instances('node', $node->type) as $instance) { $field_name = $instance['field_name']; $field = field_info_field($field_name); - if ($field['module'] == 'taxonomy' && $field['storage']['type'] == 'field_sql_storage') { + if ($field['module'] == 'entity_reference' && $field['settings']['target_type'] == 'taxonomy_term' && $field['storage']['type'] == 'field_sql_storage') { // If a field value is not set in the node object when node_save() is // called, the old value from $node->original is used. if (isset($node->{$field_name})) { @@ -1436,7 +1096,7 @@ function taxonomy_build_node_index($node) { foreach (field_available_languages('node', $field) as $langcode) { if (!empty($items[$langcode])) { foreach ($items[$langcode] as $item) { - $tid_all[$item['tid']] = $item['tid']; + $tid_all[$item['target_id']] = $item['target_id']; } } } diff --git a/core/modules/taxonomy/taxonomy.pages.inc b/core/modules/taxonomy/taxonomy.pages.inc index fbd29f1..cf77a20 100644 --- a/core/modules/taxonomy/taxonomy.pages.inc +++ b/core/modules/taxonomy/taxonomy.pages.inc @@ -78,86 +78,3 @@ function taxonomy_term_feed(Term $term) { return node_feed($nids, $channel); } -/** - * Page callback: Outputs JSON for taxonomy autocomplete suggestions. - * - * This callback outputs term name suggestions in response to Ajax requests - * made by the taxonomy autocomplete widget for taxonomy term reference - * fields. The output is a JSON object of plain-text term suggestions, keyed by - * the user-entered value with the completed term name appended. Term names - * containing commas are wrapped in quotes. - * - * For example, suppose the user has entered the string 'red fish, blue' in the - * field, and there are two taxonomy terms, 'blue fish' and 'blue moon'. The - * JSON output would have the following structure: - * @code - * { - * "red fish, blue fish": "blue fish", - * "red fish, blue moon": "blue moon", - * }; - * @endcode - * - * @param $field_name - * The name of the term reference field. - * - * @see taxonomy_menu() - * @see taxonomy_field_widget_info() - */ -function taxonomy_autocomplete($field_name) { - // A comma-separated list of term names entered in the autocomplete form - // element. Only the last term is used for autocompletion. - $tags_typed = drupal_container()->get('request')->query->get('q'); - - // Make sure the field exists and is a taxonomy field. - if (!($field = field_info_field($field_name)) || $field['type'] !== 'taxonomy_term_reference') { - // Error string. The JavaScript handler will realize this is not JSON and - // will display it as debugging information. - print t('Taxonomy field @field_name not found.', array('@field_name' => $field_name)); - exit; - } - - // The user enters a comma-separated list of tags. We only autocomplete the last tag. - $tags_typed = drupal_explode_tags($tags_typed); - $tag_last = drupal_strtolower(array_pop($tags_typed)); - - $matches = array(); - if ($tag_last != '') { - - // Part of the criteria for the query come from the field's own settings. - $vids = array(); - foreach ($field['settings']['allowed_values'] as $tree) { - $vids[] = $tree['vocabulary']; - } - - $query = db_select('taxonomy_term_data', 't'); - $query->addTag('translatable'); - $query->addTag('term_access'); - - // Do not select already entered terms. - if (!empty($tags_typed)) { - $query->condition('t.name', $tags_typed, 'NOT IN'); - } - // Select rows that match by term name. - $tags_return = $query - ->fields('t', array('tid', 'name')) - ->condition('t.vid', $vids) - ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE') - ->range(0, 10) - ->execute() - ->fetchAllKeyed(); - - $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : ''; - - $term_matches = array(); - foreach ($tags_return as $tid => $name) { - $n = $name; - // Term names containing commas or quotes must be wrapped in quotes. - if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) { - $n = '"' . str_replace('"', '""', $name) . '"'; - } - $term_matches[$prefix . $n] = check_plain($name); - } - } - - return new JsonResponse($term_matches); -} diff --git a/core/modules/taxonomy/taxonomy.views.inc b/core/modules/taxonomy/taxonomy.views.inc index 7f87670..c7cca4d 100644 --- a/core/modules/taxonomy/taxonomy.views.inc +++ b/core/modules/taxonomy/taxonomy.views.inc @@ -320,7 +320,7 @@ function taxonomy_views_data_alter(&$data) { /** * Implements hook_field_views_data(). * - * Views integration for taxonomy_term_reference fields. Adds a term relationship to the default + * Views integration for entity_reference fields. Adds a term relationship to the default * field data. * * @see field_views_field_default_views_data() 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 eac0b7f..62933e8 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 @@ -309,11 +309,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 294c97b..385480b 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..9e6fefa --- /dev/null +++ b/core/modules/user/lib/Drupal/user/Plugin/entity_reference/selection/UserSelection.php @@ -0,0 +1,148 @@ + array( + 'filter' => array( + 'type' => 'none', + ), + ), + ); + + // Add user specific filter options. + $form['filter']['type'] = array( + '#type' => 'select', + '#title' => t('Filter by'), + '#options' => array( + 'none' => t("Don't filter"), + '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/includes/ajax.inc b/core/modules/views/includes/ajax.inc index ee769a3..42fbd0a 100644 --- a/core/modules/views/includes/ajax.inc +++ b/core/modules/views/includes/ajax.inc @@ -331,7 +331,7 @@ function views_ajax_autocomplete_user($string = NULL) { * @param $vid * The vocabulary id of the tags which should be returned. * - * @see taxonomy_autocomplete() + * @see entity_reference_autocomplete_tags() */ function views_ajax_autocomplete_taxonomy($vid) { // The user enters a comma-separated list of tags. We only autocomplete the last tag. 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..e073e39 --- /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[$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/DefaultViewsTest.php b/core/modules/views/lib/Drupal/views/Tests/DefaultViewsTest.php index 1e5b72f..6979641 100644 --- a/core/modules/views/lib/Drupal/views/Tests/DefaultViewsTest.php +++ b/core/modules/views/lib/Drupal/views/Tests/DefaultViewsTest.php @@ -59,15 +59,10 @@ protected function setUp() { $this->field_name = drupal_strtolower($this->randomName()); $this->field = array( 'field_name' => $this->field_name, - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->vocabulary->id(), - 'parent' => '0', - ), - ), - ) + 'target_type' => 'taxonomy_term', + ), ); field_create_field($this->field); $this->instance = array( @@ -77,11 +72,20 @@ protected function setUp() { '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', 'page', 'full') ->setComponent($this->field_name, array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', )) ->save(); 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..8e74d44 --- /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/Tests/Wizard/TaggedWithTest.php b/core/modules/views/lib/Drupal/views/Tests/Wizard/TaggedWithTest.php index 693ed68..ba451f0 100644 --- a/core/modules/views/lib/Drupal/views/Tests/Wizard/TaggedWithTest.php +++ b/core/modules/views/lib/Drupal/views/Tests/Wizard/TaggedWithTest.php @@ -55,15 +55,10 @@ function setUp() { // Create the tag field itself. $this->tag_field = array( 'field_name' => 'field_views_testing_tags', - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->tag_vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($this->tag_field); @@ -75,20 +70,29 @@ function setUp() { 'entity_type' => 'node', 'bundle' => $this->node_type_with_tags->type, 'widget' => array( - 'type' => 'taxonomy_autocomplete', + 'type' => 'entity_reference_autocomplete_tags', + ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $this->tag_vocabulary->id(), + ), + 'auto_create' => TRUE, + ), ), ); field_create_instance($this->tag_instance); entity_get_display('node', $this->node_type_with_tags->type, 'default') ->setComponent('field_views_testing_tags', array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); entity_get_display('node', $this->node_type_with_tags->type, 'teaser') ->setComponent('field_views_testing_tags', array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); 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 @@ + 'field_' . $vocabulary->id(), - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', // Set cardinality to unlimited for tagging. 'cardinality' => FIELD_CARDINALITY_UNLIMITED, 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $vocabulary->id(), - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($field); @@ -292,22 +287,31 @@ function standard_install() { 'bundle' => 'article', 'description' => $vocabulary->help, 'widget' => array( - 'type' => 'taxonomy_autocomplete', + 'type' => 'entity_reference_autocomplete_tags', 'weight' => -4, ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $vocabulary->id(), + ), + 'auto_create' => TRUE, + ), + ), ); field_create_instance($instance); // Assign display settings for the 'default' and 'teaser' view modes. entity_get_display('node', 'article', 'default') ->setComponent($instance['field_name'], array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); entity_get_display('node', 'article', 'teaser') ->setComponent($instance['field_name'], array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_label', 'weight' => 10, )) ->save(); diff --git a/core/themes/bartik/template.php b/core/themes/bartik/template.php index 9a6c8a9..39e06aa 100644 --- a/core/themes/bartik/template.php +++ b/core/themes/bartik/template.php @@ -130,7 +130,7 @@ function bartik_menu_tree($variables) { /** * Implements theme_field__field_type(). */ -function bartik_field__taxonomy_term_reference($variables) { +function bartik_field__entity_reference($variables) { $output = ''; // Render the label, if it's not hidden.