diff --git a/core/MAINTAINERS.txt b/core/MAINTAINERS.txt index 5969d4b..185b237 100644 --- a/core/MAINTAINERS.txt +++ b/core/MAINTAINERS.txt @@ -201,6 +201,10 @@ Contextual module Database Logging module - Khalid Baheyeldin 'kbahey' http://drupal.org/user/4063 +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/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..bd93686 --- /dev/null +++ b/core/modules/entity_reference/entity_reference.module @@ -0,0 +1,517 @@ + 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', + ); + return $field_info; +} + +/** + * Implements hook_menu(). + */ +function entity_reference_menu() { + $items = array(); + + $items['entity_reference/autocomplete/single/%/%/%'] = array( + 'title' => 'Entity Reference Autocomplete', + 'page callback' => 'entity_reference_autocomplete_callback', + 'page arguments' => array(2, 3, 4, 5), + 'access callback' => 'entity_reference_autocomplete_access_callback', + 'access arguments' => array(2, 3, 4, 5), + 'type' => MENU_CALLBACK, + ); + $items['entity_reference/autocomplete/tags/%/%/%'] = array( + 'title' => 'Entity Reference Autocomplete', + 'page callback' => 'entity_reference_autocomplete_callback', + 'page arguments' => array(2, 3, 4, 5), + 'access callback' => 'entity_reference_autocomplete_access_callback', + 'access arguments' => array(2, 3, 4, 5), + 'type' => MENU_CALLBACK, + ); + + return $items; +} + +/** + * Gets the selection handler for a given entity_reference field. + */ +function entity_reference_get_selection_handler($field, $instance, EntityInterface $entity = NULL) { + $options = array( + 'field' => $field, + 'instance' => $instance, + 'entity' => $entity, + ); + return drupal_container()->get('plugin.manager.entity_reference.selection')->getInstance($options); +} + +/** + * Implements hook_field_is_empty(). + */ +function entity_reference_field_is_empty($item, $field) { + 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 (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] = '
' . 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/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) { + if ($element['#field_type'] != 'entity_reference' || $element['#formatter'] != 'entity_reference_link') { + continue; + } + $field = field_info_field($element['#field_name']); + if ($field['settings']['target_type'] !=' taxonomy_term') { + // Field doesn't reference taxonomy terms. + continue; + } + 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 + // yet and thus have no $item['taxonomy_term']. + if (isset($item['taxonomy_term'])) { $term = $item['taxonomy_term']; if (!empty($term->rdf_mapping['rdftype'])) { $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype']; 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 1ed5a4f..8b97a02 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,7 @@ function setUp() { $field = array( 'field_name' => 'field_' . $vocabulary->machine_name, - 'type' => 'taxonomy_term_reference', + 'type' => 'entity_reference', ); field_create_field($field); @@ -397,7 +397,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.install b/core/modules/forum/forum.install index 56f8402..9d52500 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->machine_name, - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), ); field_create_field($field); @@ -90,13 +85,22 @@ function forum_enable() { 'widget' => array( 'type' => 'options_select', ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $vocabulary->machine_name, + ), + 'auto_create' => TRUE, + ), + ), 'display' => array( 'default' => array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_link', 'weight' => 10, ), 'teaser' => array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_link', 'weight' => 10, ), ), 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..bce9b9b 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']; } } @@ -300,6 +300,7 @@ protected function build_filters(&$form, &$form_state) { else { $tag_field_name = reset($tag_fields); } + // @todo: Convert to entity-reference. // Add the autocomplete textfield to the wizard. $form['displays']['show']['tagged_with'] = array( '#type' => 'textfield', diff --git a/core/modules/options/options.module b/core/modules/options/options.module index e958510..e31e70b 100644 --- a/core/modules/options/options.module +++ b/core/modules/options/options.module @@ -444,14 +444,14 @@ function options_field_widget_info() { return array( 'options_select' => array( 'label' => t('Select list'), - 'field types' => array('list_integer', 'list_float', 'list_text'), + 'field types' => array('list_integer', 'list_float', 'list_text', 'entity_reference'), 'behaviors' => array( 'multiple values' => FIELD_BEHAVIOR_CUSTOM, ), ), 'options_buttons' => array( 'label' => t('Check boxes/radio buttons'), - 'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean'), + 'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean', 'entity_reference'), 'behaviors' => array( 'multiple values' => FIELD_BEHAVIOR_CUSTOM, ), diff --git a/core/modules/rdf/rdf.module b/core/modules/rdf/rdf.module index 264a090..b5a2468 100644 --- a/core/modules/rdf/rdf.module +++ b/core/modules/rdf/rdf.module @@ -789,19 +789,25 @@ 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') { - 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 - // yet and thus have no $item['taxonomy_term']. - if (isset($item['taxonomy_term'])) { - $term = $item['taxonomy_term']; - if (!empty($term->rdf_mapping['rdftype'])) { - $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype']; - } - if (!empty($term->rdf_mapping['name']['predicates'])) { - $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates']; - } + if ($element['#field_type'] != 'entity_reference' || $element['#formatter'] != 'entity_reference_link') { + continue; + } + $field = field_info_field($element['#field_name']); + if ($field['settings']['target_type'] !=' taxonomy_term') { + // Field doesn't reference taxonomy terms. + continue; + } + 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 + // yet and thus have no $item['taxonomy_term']. + if (isset($item['taxonomy_term'])) { + $term = $item['taxonomy_term']; + if (!empty($term->rdf_mapping['rdftype'])) { + $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype']; + } + if (!empty($term->rdf_mapping['name']['predicates'])) { + $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates']; } } } 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 b876a53..4e57890 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php @@ -81,7 +81,10 @@ 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->machine_name; field_create_field($field); 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..c1355b5 --- /dev/null +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/entity_reference/selection/TermSelection.php @@ -0,0 +1,148 @@ + 'value', + '#default_vaulue' => !empty($instance['settings']['handler_settings']['parent']) ? $instance['settings']['handler_settings']['parent'] : 0, + ); + + return $form; + } + + /** + * Overrides SelectionBase::buildEntityQuery(). + * + * @todo: Split SelectionBase::buildEntityQuery() so it's easier to + * override? + */ + 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. + + // We have the machine name, but we need to translate it to VID, so + // we can use entity_query(). + $vids = array(); + foreach ($this->instance['settings']['handler_settings']['target_bundles'] as $name) { + $vocabulary = taxonomy_vocabulary_machine_name_load($name); + $vids[] = $vocabulary->vid; + } + + $query->condition('vid', $vids, '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; + } + + /** + * Overrides SelectionBase::entityQueryAlter(). + */ + public function entityQueryAlter(SelectInterface $query) { + // The Taxonomy module doesn't implement any proper taxonomy term access, + // and as a consequence doesn't make sure that taxonomy terms cannot be + // viewed when the user doesn't have access to the vocabulary. + $tables = $query->getTables(); + $base_table = $tables['base_table']['alias']; + $vocabulary_alias = $query->innerJoin('taxonomy_vocabulary', 'n', '%alias.vid = ' . $base_table . '.vid'); + $query->addMetadata('base_table', $vocabulary_alias); + // Pass the query to the taxonomy access control. + $this->reAlterQuery($query, 'taxonomy_vocabulary_access', $vocabulary_alias); + + // Also, the taxonomy term entity exposes a bundle, but doesn't have a + // bundle column in the database. We have to alter the query ourselves to go + // fetch the bundle. + $conditions = &$query->conditions(); + foreach ($conditions as $key => &$condition) { + if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'vocabulary_machine_name') { + $condition['field'] = $vocabulary_alias . '.machine_name'; + break; + } + } + } + + /** + * Overrides SelectionBase::getReferencableEntities(). + */ + public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { + if ($match || $limit) { + return parent::getReferencableEntities($match , $match_operator, $limit); + } + + $options = array(); + + // We imitate core by calling taxonomy_get_tree(). + $entity_info = entity_get_info('taxonomy_term'); + $bundles = !empty($this->instance['settings']['handler_settings']['target_bundles']) ? $this->instance['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']); + $parent = !empty($this->instance['settings']['handler_settings']['parent']) ? $this->instance['settings']['handler_settings']['parent'] : 0; + + foreach ($bundles as $bundle) { + if ($vocabulary = taxonomy_vocabulary_machine_name_load($bundle)) { + if ($terms = taxonomy_get_tree($vocabulary->vid, $parent, NULL, TRUE)) { + foreach ($terms as $term) { + $options[$vocabulary->machine_name][$term->tid] = str_repeat('-', $term->depth) . check_plain($term->label()); + } + } + } + } + + return $options; + } +} diff --git a/core/modules/taxonomy/taxonomy.module b/core/modules/taxonomy/taxonomy.module index 8f8a52c..bfa6b35 100644 --- a/core/modules/taxonomy/taxonomy.module +++ b/core/modules/taxonomy/taxonomy.module @@ -999,53 +999,6 @@ 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. - * - 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 @@ -1055,6 +1008,8 @@ function taxonomy_options_list($field, $instance, $entity_type, $entity) { * * Possible error codes: * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values. + * + * @todo: Do we need to keep anything here? */ 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 @@ -1105,28 +1060,11 @@ function taxonomy_field_validate($entity_type, $entity, $field, $instance, $lang } /** - * 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'), - ), + // @todo: Have a generic formatter for RSS? 'taxonomy_term_reference_rss_category' => array( 'label' => t('RSS category'), 'field types' => array('taxonomy_term_reference'), @@ -1145,35 +1083,7 @@ function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, // 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; - + // @todo: Have a generic formatter for RSS? case 'taxonomy_term_reference_rss_category': foreach ($items as $delta => $item) { $entity->rss_elements[] = array( @@ -1190,87 +1100,6 @@ function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, 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_machine_name_load($tree['vocabulary'])) { - if ($terms = taxonomy_get_tree($vocabulary->vid, $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. 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..8ab9ca3 100644 --- a/core/modules/views/includes/ajax.inc +++ b/core/modules/views/includes/ajax.inc @@ -332,6 +332,8 @@ function views_ajax_autocomplete_user($string = NULL) { * The vocabulary id of the tags which should be returned. * * @see taxonomy_autocomplete() + * + * @todo Convert to Entity-reference. */ 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..ea6bd2e --- /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.') . '
' . 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()] = $result[$entity->id()]; + } + } + return $return; + } + + /** + * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::countReferencableEntities(). + */ + public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') { + $this->getReferencableEntities($match, $match_operator); + return $this->view->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 7e37452..aafc3e9 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->machine_name, - 'parent' => '0', - ), - ), - ) + 'target_type' => 'taxonomy_term', + ), ); field_create_field($this->field); $this->instance = array( @@ -77,6 +72,15 @@ protected function setUp() { 'widget' => array( 'type' => 'options_select', ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $this->vocabulary->machine_name, + ), + 'auto_create' => TRUE, + ), + ), 'display' => array( 'full' => array( 'type' => 'taxonomy_term_reference_link', 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 cf3d19e..660cdab 100644 --- a/core/modules/views/lib/Drupal/views/Tests/Wizard/TaggedWithTest.php +++ b/core/modules/views/lib/Drupal/views/Tests/Wizard/TaggedWithTest.php @@ -55,16 +55,11 @@ function setUp() { // Create the tag field itself. $this->tag_field = array( 'field_name' => 'field_views_testing_tags', - 'type' => 'taxonomy_term_reference', - 'cardinality' => FIELD_CARDINALITY_UNLIMITED, + 'type' => 'entity_reference', 'settings' => array( - 'allowed_values' => array( - array( - 'vocabulary' => $this->tag_vocabulary->machine_name, - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term', ), + 'cardinality' => FIELD_CARDINALITY_UNLIMITED, ); field_create_field($this->tag_field); @@ -75,15 +70,24 @@ function setUp() { 'entity_type' => 'node', 'bundle' => $this->node_type_with_tags->type, 'widget' => array( - 'type' => 'taxonomy_autocomplete', + 'type' => 'entity_reference_autocomplete', + ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $this->tag_vocabulary->machine_name, + ), + 'auto_create' => TRUE, + ), ), 'display' => array( 'default' => array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_link', 'weight' => 10, ), 'teaser' => array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_link', 'weight' => 10, ), ), 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->machine_name, - '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->machine_name, - 'parent' => 0, - ), - ), + 'target_type' => 'taxonomy_term' ), ); field_create_field($field); @@ -292,16 +287,25 @@ function standard_install() { 'bundle' => 'article', 'description' => $vocabulary->help, 'widget' => array( - 'type' => 'taxonomy_autocomplete', + 'type' => 'entity_reference_autocomplete', 'weight' => -4, ), + 'settings' => array( + 'handler' => 'base', + 'handler_settings' => array( + 'target_bundles' => array( + $vocabulary->machine_name, + ), + 'auto_create' => TRUE, + ), + ), 'display' => array( 'default' => array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_link', 'weight' => 10, ), 'teaser' => array( - 'type' => 'taxonomy_term_reference_link', + 'type' => 'entity_reference_link', 'weight' => 10, ), ), diff --git a/core/themes/bartik/template.php b/core/themes/bartik/template.php index 9a6c8a9..a0b3bca 100644 --- a/core/themes/bartik/template.php +++ b/core/themes/bartik/template.php @@ -129,6 +129,8 @@ function bartik_menu_tree($variables) { /** * Implements theme_field__field_type(). + * + * @todo: Adapt to Entity-reference. */ function bartik_field__taxonomy_term_reference($variables) { $output = '';