updated core and modules

This commit is contained in:
Bachir Soussi Chiadmi
2017-09-09 16:27:51 +02:00
parent 027aa99b32
commit 41863f872c
7810 changed files with 318922 additions and 83631 deletions
+2 -2
View File
@@ -85,7 +85,7 @@ function hook_field_storage_config_update_forbid(\Drupal\field\FieldStorageConfi
$prior_allowed_values = $prior_field_storage->getSetting('allowed_values');
$lost_keys = array_keys(array_diff_key($prior_allowed_values, $allowed_values));
if (_options_values_in_use($field_storage->getTargetEntityTypeId(), $field_storage->getName(), $lost_keys)) {
throw new \Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException(t('A list field (@field_name) with existing data cannot have its keys changed.', array('@field_name' => $field_storage->getName())));
throw new \Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException(t('A list field (@field_name) with existing data cannot have its keys changed.', ['@field_name' => $field_storage->getName()]));
}
}
}
@@ -257,7 +257,7 @@ function hook_field_formatter_info_alter(array &$info) {
* @ingroup field_info
*/
function hook_field_info_max_weight($entity_type, $bundle, $context, $context_mode) {
$weights = array();
$weights = [];
foreach (my_module_entity_additions($entity_type, $bundle, $context, $context_mode) as $addition) {
$weights[] = $addition['weight'];
+3 -3
View File
@@ -5,8 +5,8 @@ package: Core
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
+16 -15
View File
@@ -1,4 +1,5 @@
<?php
/**
* @file
* Attach custom data fields to Drupal entities.
@@ -66,10 +67,10 @@ require_once __DIR__ . '/field.purge.inc';
function field_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.field':
$field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#';
$field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#';
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Field module allows custom data fields to be defined for <em>entity</em> types (see below). The Field module takes care of storing, loading, editing, and rendering field data. Most users will not interact with the Field module directly, but will instead use the <a href=":field-ui-help">Field UI module</a> user interface. Module developers can use the Field API to make new entity types "fieldable" and thus allow fields to be attached to them. For more information, see the <a href=":field">online documentation for the Field module</a>.', array(':field-ui-help' => $field_ui_url, ':field' => 'https://www.drupal.org/documentation/modules/field')) . '</p>';
$output .= '<p>' . t('The Field module allows custom data fields to be defined for <em>entity</em> types (see below). The Field module takes care of storing, loading, editing, and rendering field data. Most users will not interact with the Field module directly, but will instead use the <a href=":field-ui-help">Field UI module</a> user interface. Module developers can use the Field API to make new entity types "fieldable" and thus allow fields to be attached to them. For more information, see the <a href=":field">online documentation for the Field module</a>.', [':field-ui-help' => $field_ui_url, ':field' => 'https://www.drupal.org/documentation/modules/field']) . '</p>';
$output .= '<h3>' . t('Terminology') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Entities and entity types') . '</dt>';
@@ -86,19 +87,19 @@ function field_help($route_name, RouteMatchInterface $route_match) {
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Enabling field types, widgets, and formatters') . '</dt>';
$output .= '<dd>' . t('The Field module provides the infrastructure for fields; the field types, formatters, and widgets are provided by Drupal core or additional modules. Some of the modules are required; the optional modules can be enabled from the <a href=":modules">Extend administration page</a>. Additional fields, formatters, and widgets may be provided by contributed modules, which you can find in the <a href=":contrib">contributed module section of Drupal.org</a>.', array(':modules' => \Drupal::url('system.modules_list'), ':contrib' => 'https://www.drupal.org/project/modules')) . '</dd>';
$output .= '<dd>' . t('The Field module provides the infrastructure for fields; the field types, formatters, and widgets are provided by Drupal core or additional modules. Some of the modules are required; the optional modules can be enabled from the <a href=":modules">Extend administration page</a>. Additional fields, formatters, and widgets may be provided by contributed modules, which you can find in the <a href=":contrib">contributed module section of Drupal.org</a>.', [':modules' => \Drupal::url('system.modules_list'), ':contrib' => 'https://www.drupal.org/project/modules']) . '</dd>';
$output .= '<h3>' . t('Field, widget, and formatter information') . '</h3>';
// Make a list of all widget, formatter, and field modules currently
// enabled, ordered by displayed module name (module names are not
// translated).
$items = array();
$items = [];
$modules = \Drupal::moduleHandler()->getModuleList();
$widgets = \Drupal::service('plugin.manager.field.widget')->getDefinitions();
$field_types = \Drupal::service('plugin.manager.field.field_type')->getUiDefinitions();
$formatters = \Drupal::service('plugin.manager.field.formatter')->getDefinitions();
$providers = array();
$providers = [];
foreach (array_merge($field_types, $widgets, $formatters) as $plugin) {
$providers[] = $plugin['provider'];
}
@@ -110,7 +111,7 @@ function field_help($route_name, RouteMatchInterface $route_match) {
if (isset($modules[$provider])) {
$display = \Drupal::moduleHandler()->getName($provider);
if (\Drupal::moduleHandler()->implementsHook($provider, 'help')) {
$items[] = \Drupal::l($display, new Url('help.page', array('name' => $provider)));
$items[] = \Drupal::l($display, new Url('help.page', ['name' => $provider]));
}
else {
$items[] = $display;
@@ -120,10 +121,10 @@ function field_help($route_name, RouteMatchInterface $route_match) {
if ($items) {
$output .= '<dt>' . t('Provided by modules') . '</dt>';
$output .= '<dd>' . t('Here is a list of the currently enabled field, formatter, and widget modules:');
$item_list = array(
$item_list = [
'#theme' => 'item_list',
'#items' => $items,
);
];
$output .= \Drupal::service('renderer')->renderPlain($item_list);
$output .= '</dd>';
}
@@ -131,10 +132,10 @@ function field_help($route_name, RouteMatchInterface $route_match) {
$output .= '<dt>' . t('Provided by Drupal core') . '</dt>';
$output .= '<dd>' . t('As mentioned previously, some field types, widgets, and formatters are provided by Drupal core. Here are some notes on how to use some of these:');
$output .= '<ul>';
$output .= '<li><p>' . t('<strong>Entity Reference</strong> fields allow you to create fields that contain links to other entities (such as content items, taxonomy terms, etc.) within the site. This allows you, for example, to include a link to a user within a content item. For more information, see <a href=":er_do">the online documentation for the Entity Reference module</a>.', array(':er_do' => 'https://drupal.org/documentation/modules/entityreference')) . '</p>';
$output .= '<li><p>' . t('<strong>Entity Reference</strong> fields allow you to create fields that contain links to other entities (such as content items, taxonomy terms, etc.) within the site. This allows you, for example, to include a link to a user within a content item. For more information, see <a href=":er_do">the online documentation for the Entity Reference module</a>.', [':er_do' => 'https://drupal.org/documentation/modules/entityreference']) . '</p>';
$output .= '<dl>';
$output .= '<dt>' . t('Managing and displaying entity reference fields') . '</dt>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the entity reference field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', array(':field_ui' => $field_ui_url)) . '</dd>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the entity reference field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => $field_ui_url]) . '</dd>';
$output .= '<dt>' . t('Selecting reference type') . '</dt>';
$output .= '<dd>' . t('In the field settings you can select which entity type you want to create a reference to.') . '</dd>';
$output .= '<dt>' . t('Filtering and sorting reference fields') . '</dt>';
@@ -178,7 +179,7 @@ function field_entity_field_storage_info(EntityTypeInterface $entity_type) {
->execute();
// Fetch all fields and key them by field name.
$field_storages = FieldStorageConfig::loadMultiple($ids);
$result = array();
$result = [];
foreach ($field_storages as $field_storage) {
$result[$field_storage->getName()] = $field_storage;
}
@@ -199,7 +200,7 @@ function field_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundl
->execute();
// Fetch all fields and key them by field name.
$field_configs = FieldConfig::loadMultiple($ids);
$result = array();
$result = [];
foreach ($field_configs as $field_instance) {
$result[$field_instance->getName()] = $field_instance;
}
@@ -282,7 +283,7 @@ function field_entity_bundle_delete($entity_type_id, $bundle) {
* An entity, initialized with the provided IDs.
*/
function _field_create_entity_from_ids($ids) {
$id_properties = array();
$id_properties = [];
$entity_type = \Drupal::entityManager()->getDefinition($ids->entity_type);
if ($id_key = $entity_type->getKey('id')) {
$id_properties[$id_key] = $ids->entity_id;
@@ -310,7 +311,7 @@ function field_config_import_steps_alter(&$sync_steps, ConfigImporter $config_im
// Add a step to the beginning of the configuration synchronization process
// to purge field data where the module that provides the field is being
// uninstalled.
array_unshift($sync_steps, array('\Drupal\field\ConfigImporterFieldPurger', 'process'));
array_unshift($sync_steps, ['\Drupal\field\ConfigImporterFieldPurger', 'process']);
};
}
@@ -340,7 +341,7 @@ function field_form_config_admin_import_form_alter(&$form, FormStateInterface $f
count($field_storages),
'This synchronization will delete data from the field %fields.',
'This synchronization will delete data from the fields: %fields.',
array('%fields' => implode(', ', $field_labels))
['%fields' => implode(', ', $field_labels)]
), 'warning');
}
}
-17
View File
@@ -9,10 +9,6 @@ use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
/**
* @addtogroup updates-8.0.0-beta
* @{
*/
/**
* Re-save all field storage config objects to add 'custom_storage' property.
@@ -42,15 +38,6 @@ function field_post_update_entity_reference_handler_setting() {
return t('Selection handler for entity reference fields have been adjusted.');
}
/**
* @} End of "addtogroup updates-8.0.0-beta".
*/
/**
* @addtogroup updates-8.1.0
* @{
*/
/**
* Adds the 'size' setting for email widgets.
*/
@@ -72,7 +59,3 @@ function field_post_update_email_widget_size_setting() {
return t('The new size setting for email widgets has been added.');
}
/**
* @} End of "addtogroup updates-8.1.0".
*/
+11 -11
View File
@@ -21,9 +21,9 @@ use Drupal\field\FieldConfigInterface;
*
* When a single entity is deleted, the Entity storage performs the
* following operations:
* - Invoking the FieldItemListInterface delete() method for each field on the
* entity. A file field type might use this method to delete uploaded files
* from the filesystem.
* - Invoking the method \Drupal\Core\Field\FieldItemListInterface::delete() for
* each field on the entity. A file field type might use this method to delete
* uploaded files from the filesystem.
* - Removing the data from storage.
* - Invoking the global hook_entity_delete() for all modules that implement it.
* Each hook implementation receives the entity being deleted and can operate
@@ -73,10 +73,10 @@ use Drupal\field\FieldConfigInterface;
* (optional) Limit the purge to a specific field storage.
*/
function field_purge_batch($batch_size, $field_storage_uuid = NULL) {
$properties = array(
$properties = [
'deleted' => TRUE,
'include_deleted' => TRUE,
);
];
if ($field_storage_uuid) {
$properties['field_storage_uuid'] = $field_storage_uuid;
}
@@ -106,7 +106,7 @@ function field_purge_batch($batch_size, $field_storage_uuid = NULL) {
}
// Retrieve all deleted field storages. Any that have no fields can be purged.
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array();
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: [];
foreach ($deleted_storages as $field_storage) {
$field_storage = new FieldStorageConfig($field_storage);
if ($field_storage_uuid && $field_storage->uuid() != $field_storage_uuid) {
@@ -121,7 +121,7 @@ function field_purge_batch($batch_size, $field_storage_uuid = NULL) {
continue;
}
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
if (empty($fields)) {
field_purge_field_storage($field_storage);
}
@@ -144,7 +144,7 @@ function field_purge_field(FieldConfigInterface $field) {
$state->set('field.field.deleted', $deleted_fields);
// Invoke external hooks after the cache is cleared for API consistency.
\Drupal::moduleHandler()->invokeAll('field_purge_field', array($field));
\Drupal::moduleHandler()->invokeAll('field_purge_field', [$field]);
}
/**
@@ -159,9 +159,9 @@ function field_purge_field(FieldConfigInterface $field) {
* @throws Drupal\field\FieldException
*/
function field_purge_field_storage(FieldStorageConfigInterface $field_storage) {
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
if (count($fields) > 0) {
throw new FieldException(t('Attempt to purge a field storage @field_name that still has fields.', array('@field_name' => $field_storage->getName())));
throw new FieldException(t('Attempt to purge a field storage @field_name that still has fields.', ['@field_name' => $field_storage->getName()]));
}
$state = \Drupal::state();
@@ -173,7 +173,7 @@ function field_purge_field_storage(FieldStorageConfigInterface $field_storage) {
\Drupal::entityManager()->getStorage($field_storage->getTargetEntityTypeId())->finalizePurge($field_storage);
// Invoke external hooks after the cache is cleared for API consistency.
\Drupal::moduleHandler()->invokeAll('field_purge_field_storage', array($field_storage));
\Drupal::moduleHandler()->invokeAll('field_purge_field_storage', [$field_storage]);
}
/**
@@ -15,105 +15,101 @@ process:
langcode: 'constants/langcode'
field_name: field_name
type:
-
plugin: field_type
source:
- type
- widget_type
map:
number_integer:
number: integer
optionwidgets_select: list_integer
optionwidgets_buttons: list_integer
optionwidgets_onoff: boolean
number_decimal:
number: decimal
optionwidgets_select: list_float
optionwidgets_buttons: list_float
optionwidgets_onoff: boolean
number_float:
number: float
optionwidgets_select: list_float
optionwidgets_buttons: list_float
optionwidgets_onoff: boolean
email:
email_textfield: email
filefield:
imagefield_widget: image
filefield_widget: file
date:
date_select: datetime
datestamp:
date_select: datetime
datetime:
date_select: datetime
fr_phone:
phone_textfield: telephone
be_phone:
phone_textfield: telephone
it_phone:
phone_textfield: telephone
el_phone:
phone_textfield: telephone
ch_phone:
phone_textfield: telephone
ca_phone:
phone_textfield: telephone
cr_phone:
phone_textfield: telephone
pa_phone:
phone_textfield: telephone
gb_phone:
phone_textfield: telephone
ru_phone:
phone_textfield: telephone
ua_phone:
phone_textfield: telephone
es_phone:
phone_textfield: telephone
au_phone:
phone_textfield: telephone
cs_phone:
phone_textfield: telephone
hu_phone:
phone_textfield: telephone
pl_phone:
phone_textfield: telephone
nl_phone:
phone_textfield: telephone
se_phone:
phone_textfield: telephone
za_phone:
phone_textfield: telephone
il_phone:
phone_textfield: telephone
nz_phone:
phone_textfield: telephone
br_phone:
phone_textfield: telephone
cl_phone:
phone_textfield: telephone
cn_phone:
phone_textfield: telephone
hk_phone:
phone_textfield: telephone
mo_phone:
phone_textfield: telephone
ph_phone:
phone_textfield: telephone
sg_phone:
phone_textfield: telephone
jo_phone:
phone_textfield: telephone
eg_phone:
phone_textfield: telephone
pk_phone:
phone_textfield: telephone
int_phone:
phone_textfield: telephone
-
plugin: skip_on_empty
method: row
plugin: field_type
source:
- type
- widget_type
map:
userreference:
userreference_select: entity_reference
userreference_buttons: entity_reference
userreference_autocomplete: entity_reference
nodereference:
nodereference_select: entity_reference
number_integer:
number: integer
optionwidgets_select: list_integer
optionwidgets_buttons: list_integer
optionwidgets_onoff: boolean
number_decimal:
number: decimal
optionwidgets_select: list_float
optionwidgets_buttons: list_float
optionwidgets_onoff: boolean
number_float:
number: float
optionwidgets_select: list_float
optionwidgets_buttons: list_float
optionwidgets_onoff: boolean
email:
email_textfield: email
filefield:
imagefield_widget: image
filefield_widget: file
fr_phone:
phone_textfield: telephone
be_phone:
phone_textfield: telephone
it_phone:
phone_textfield: telephone
el_phone:
phone_textfield: telephone
ch_phone:
phone_textfield: telephone
ca_phone:
phone_textfield: telephone
cr_phone:
phone_textfield: telephone
pa_phone:
phone_textfield: telephone
gb_phone:
phone_textfield: telephone
ru_phone:
phone_textfield: telephone
ua_phone:
phone_textfield: telephone
es_phone:
phone_textfield: telephone
au_phone:
phone_textfield: telephone
cs_phone:
phone_textfield: telephone
hu_phone:
phone_textfield: telephone
pl_phone:
phone_textfield: telephone
nl_phone:
phone_textfield: telephone
se_phone:
phone_textfield: telephone
za_phone:
phone_textfield: telephone
il_phone:
phone_textfield: telephone
nz_phone:
phone_textfield: telephone
br_phone:
phone_textfield: telephone
cl_phone:
phone_textfield: telephone
cn_phone:
phone_textfield: telephone
hk_phone:
phone_textfield: telephone
mo_phone:
phone_textfield: telephone
ph_phone:
phone_textfield: telephone
sg_phone:
phone_textfield: telephone
jo_phone:
phone_textfield: telephone
eg_phone:
phone_textfield: telephone
pk_phone:
phone_textfield: telephone
int_phone:
phone_textfield: telephone
cardinality:
plugin: static_map
bypass: true
@@ -126,6 +122,6 @@ process:
source:
- '@type'
- global_settings
- type
destination:
plugin: md_entity:field_storage_config
plugin: entity:field_storage_config
@@ -15,7 +15,7 @@ process:
# field migration.
field_type_exists:
-
plugin: migration
plugin: migration_lookup
migration: d6_field
source:
- field_name
@@ -29,7 +29,7 @@ process:
entity_type: 'constants/entity_type'
bundle:
-
plugin: migration
plugin: migration_lookup
migration: d6_node_type
source: type_name
-
@@ -37,7 +37,7 @@ process:
method: row
view_mode:
-
plugin: migration
plugin: migration_lookup
migration: d6_view_modes
source:
- view_mode
@@ -163,6 +163,14 @@ process:
default: basic_string
int_phone:
default: basic_string
nodereference:
default: entity_reference_label
plain: entity_reference_label
full: entity_reference_entity_view
teaser: entity_reference_entity_view
userreference:
default: entity_reference_label
plain: entity_reference_label
-
plugin: field_type_defaults
"options/settings":
@@ -173,6 +181,18 @@ process:
- module
- 'display_settings/format'
map:
nodereference:
default: { }
plain:
link: false
full:
view_mode: full
teaser:
view_mode: teaser
userreference:
default: { }
plain:
link: false
link:
default:
trim_length: '80'
@@ -14,7 +14,7 @@ process:
# field migration.
field_type_exists:
-
plugin: migration
plugin: migration_lookup
migration: d6_field
source:
- field_name
@@ -29,7 +29,7 @@ process:
field_name: field_name
bundle:
-
plugin: migration
plugin: migration_lookup
migration: d6_node_type
source: type_name
-
@@ -16,7 +16,7 @@ process:
# field migration.
field_type_exists:
-
plugin: migration
plugin: migration_lookup
migration: d6_field
source:
- field_name
@@ -29,7 +29,7 @@ process:
method: row
bundle:
-
plugin: migration
plugin: migration_lookup
migration: d6_node_type
source: type_name
-
@@ -49,11 +49,14 @@ process:
email_textfield: email_default
date_select: datetime_default
date_text: datetime_default
date_popup: datetime_default
imagefield_widget: image_image
phone_textfield: telephone_default
optionwidgets_onoff: boolean_checkbox
optionwidgets_buttons: options_buttons
optionwidgets_select: options_select
nodereference_select: options_select
userreference_select: options_select
'options/settings':
-
plugin: field_instance_widget_settings
@@ -22,6 +22,7 @@ process:
datestamp: datetime
datetime: datetime
email: email
entityreference: entity_reference
file: file
image: image
link_field: link
@@ -34,7 +35,10 @@ process:
phone: telephone
text_long: text_long
text_with_summary: text_with_summary
translatable: translatable
# Translatable is not migrated and the Drupal 8 default of true is used.
# If translatable is false in field storage then the field can not be
# set to translatable via the UI.
#translatable: translatable
cardinality: cardinality
settings:
plugin: d7_field_settings
@@ -13,7 +13,7 @@ process:
# field migration.
field_type_exists:
-
plugin: migration
plugin: migration_lookup
migration: d7_field
source:
- field_name
@@ -29,7 +29,7 @@ process:
bundle: bundle
view_mode:
-
plugin: migration
plugin: migration_lookup
migration: d7_view_modes
source:
- entity_type
@@ -51,7 +51,7 @@ process:
-
plugin: static_map
bypass: true
source: type
source: formatter_type
map:
date_default: datetime_default
email_default: email_mailto
@@ -61,6 +61,9 @@ process:
link_default: link
phone: basic_string
taxonomy_term_reference_link: entity_reference_label
entityreference_label: entity_reference_label
entityreference_entity_id: entity_reference_entity_id
entityreference_entity_view: entity_reference_entity_view
-
plugin: skip_on_empty
method: row
@@ -21,12 +21,14 @@ process:
source:
- instance_settings
- widget_settings
- field_settings
default_value_function: ''
default_value:
plugin: d7_field_instance_defaults
source:
- default_value
- widget_settings
translatable: translatable
destination:
plugin: entity:field_config
migration_dependencies:
@@ -35,3 +37,4 @@ migration_dependencies:
optional:
- d7_node_type
- d7_comment_type
- d7_taxonomy_vocabulary
@@ -14,7 +14,7 @@ process:
# field migration.
field_type_exists:
-
plugin: migration
plugin: migration_lookup
migration: d7_field
source:
- field_name
@@ -46,6 +46,7 @@ process:
phone_textfield: telephone_default
options_onoff: boolean_checkbox
entityreference_autocomplete: entity_reference_autocomplete
entityreference_autocomplete_tags: entity_reference_autocomplete_tags
taxonomy_autocomplete: entity_reference_autocomplete
'options/settings':
plugin: field_instance_widget_settings
@@ -47,7 +47,7 @@ class ConfigImporterFieldPurger {
}
else {
$context['finished'] = $context['sandbox']['field']['current_progress'] / $context['sandbox']['field']['steps_to_delete'];
$context['message'] = \Drupal::translation()->translate('Purging field @field_label', array('@field_label' => $field_storage->label()));
$context['message'] = \Drupal::translation()->translate('Purging field @field_label', ['@field_label' => $field_storage->label()]);
}
}
@@ -111,11 +111,11 @@ class ConfigImporterFieldPurger {
public static function getFieldStoragesToPurge(array $extensions, array $deletes) {
$providers = array_keys($extensions['module']);
$providers[] = 'core';
$storages_to_delete = array();
$storages_to_delete = [];
// Gather fields that will be deleted during configuration synchronization
// where the module that provides the field type is also being uninstalled.
$field_storage_ids = array();
$field_storage_ids = [];
foreach ($deletes as $config_name) {
$field_storage_config_prefix = \Drupal::entityManager()->getDefinition('field_storage_config')->getConfigPrefix();
if (strpos($config_name, $field_storage_config_prefix . '.') === 0) {
@@ -134,7 +134,7 @@ class ConfigImporterFieldPurger {
// Gather deleted fields from modules that are being uninstalled.
/** @var \Drupal\field\FieldStorageConfigInterface[] $field_storages */
$field_storages = entity_load_multiple_by_properties('field_storage_config', array('deleted' => TRUE, 'include_deleted' => TRUE));
$field_storages = entity_load_multiple_by_properties('field_storage_config', ['deleted' => TRUE, 'include_deleted' => TRUE]);
foreach ($field_storages as $field_storage) {
if (!in_array($field_storage->getTypeProvider(), $providers)) {
$storages_to_delete[$field_storage->id()] = $field_storage;
@@ -193,7 +193,7 @@ class FieldConfig extends FieldConfigBase implements FieldConfigInterface {
parent::preDelete($storage, $fields);
// Keep the field definitions in the state storage so we can use them
// later during field_purge_batch().
$deleted_fields = $state->get('field.field.deleted') ?: array();
$deleted_fields = $state->get('field.field.deleted') ?: [];
foreach ($fields as $field) {
if (!$field->deleted) {
$config = $field->toArray();
@@ -228,7 +228,7 @@ class FieldConfig extends FieldConfigBase implements FieldConfigInterface {
// Delete the associated field storages if they are not used anymore and are
// not persistent.
$storages_to_delete = array();
$storages_to_delete = [];
foreach ($fields as $field) {
$storage_definition = $field->getFieldStorageDefinition();
if (!$field->deleted && !$field->isUninstalling() && $storage_definition->isDeletable()) {
@@ -306,7 +306,7 @@ class FieldConfig extends FieldConfigBase implements FieldConfigInterface {
*/
public function getDisplayOptions($display_context) {
// Hide configurable fields by default.
return array('type' => 'hidden');
return ['region' => 'hidden'];
}
/**
@@ -18,6 +18,7 @@ use Drupal\field\FieldStorageConfigInterface;
* id = "field_storage_config",
* label = @Translation("Field storage"),
* handlers = {
* "access" = "Drupal\field\FieldStorageConfigAccessControlHandler",
* "storage" = "Drupal\field\FieldStorageConfigStorage"
* },
* config_prefix = "storage",
@@ -370,7 +371,7 @@ class FieldStorageConfig extends ConfigEntityBase implements FieldStorageConfigI
// See if any module forbids the update by throwing an exception. This
// invokes hook_field_storage_config_update_forbid().
$module_handler->invokeAll('field_storage_config_update_forbid', array($this, $this->original));
$module_handler->invokeAll('field_storage_config_update_forbid', [$this, $this->original]);
// Notify the entity manager. A listener can reject the definition
// update as invalid by raising an exception, which stops execution before
@@ -407,7 +408,7 @@ class FieldStorageConfig extends ConfigEntityBase implements FieldStorageConfigI
// Keep the field definitions in the state storage so we can use them later
// during field_purge_batch().
$deleted_storages = $state->get('field.storage.deleted') ?: array();
$deleted_storages = $state->get('field.storage.deleted') ?: [];
foreach ($field_storages as $field_storage) {
if (!$field_storage->deleted) {
$config = $field_storage->toArray();
@@ -444,12 +445,12 @@ class FieldStorageConfig extends ConfigEntityBase implements FieldStorageConfigI
$class = $this->getFieldItemClass();
$schema = $class::schema($this);
// Fill in default values for optional entries.
$schema += array(
'columns' => array(),
'unique keys' => array(),
'indexes' => array(),
'foreign keys' => array(),
);
$schema += [
'columns' => [],
'unique keys' => [],
'indexes' => [],
'foreign keys' => [],
];
// Merge custom indexes with those specified by the field type. Custom
// indexes prevail.
@@ -499,7 +500,7 @@ class FieldStorageConfig extends ConfigEntityBase implements FieldStorageConfigI
return $map[$this->getTargetEntityTypeId()][$this->getName()]['bundles'];
}
}
return array();
return [];
}
/**
@@ -719,7 +720,7 @@ class FieldStorageConfig extends ConfigEntityBase implements FieldStorageConfigI
* {@inheritdoc}
*/
public function getConstraints() {
return array();
return [];
}
/**
@@ -2,13 +2,12 @@
namespace Drupal\field;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Defines the access control handler for the field entity type.
* Defines the access control handler for the field config entity type.
*
* @see \Drupal\field\Entity\FieldConfig
*/
@@ -18,16 +17,16 @@ class FieldConfigAccessControlHandler extends EntityAccessControlHandler {
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
if ($operation == 'delete') {
$field_storage_entity = $entity->getFieldStorageDefinition();
if ($field_storage_entity->isLocked()) {
return AccessResult::forbidden()->addCacheableDependency($field_storage_entity);
}
else {
return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields')->addCacheableDependency($field_storage_entity);
}
}
return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields');
// Delegate access control to the underlying field storage config entity:
// the field config entity merely handles configuration for a particular
// bundle of an entity type, the bulk of the logic and configuration is with
// the field storage config entity. Therefore, if an operation is allowed on
// a certain field storage config entity, it should also be allowed for all
// associated field config entities.
// @see \Drupal\Core\Field\FieldDefinitionInterface
/** \Drupal\field\FieldConfigInterface $entity */
$field_storage_entity = $entity->getFieldStorageDefinition();
return $field_storage_entity->access($operation, $account, TRUE);
}
}
@@ -95,12 +95,12 @@ class FieldConfigStorage extends FieldConfigStorageBase {
/**
* {@inheritdoc}
*/
public function loadByProperties(array $conditions = array()) {
public function loadByProperties(array $conditions = []) {
// Include deleted fields if specified in the $conditions parameters.
$include_deleted = isset($conditions['include_deleted']) ? $conditions['include_deleted'] : FALSE;
unset($conditions['include_deleted']);
$fields = array();
$fields = [];
// Get fields stored in configuration. If we are explicitly looking for
// deleted fields only, this can be skipped, because they will be
@@ -109,7 +109,7 @@ class FieldConfigStorage extends FieldConfigStorageBase {
if (isset($conditions['entity_type']) && isset($conditions['bundle']) && isset($conditions['field_name'])) {
// Optimize for the most frequent case where we do have a specific ID.
$id = $conditions['entity_type'] . '.' . $conditions['bundle'] . '.' . $conditions['field_name'];
$fields = $this->loadMultiple(array($id));
$fields = $this->loadMultiple([$id]);
}
else {
// No specific ID, we need to examine all existing fields.
@@ -119,8 +119,8 @@ class FieldConfigStorage extends FieldConfigStorageBase {
// Merge deleted fields (stored in state) if needed.
if ($include_deleted || !empty($conditions['deleted'])) {
$deleted_fields = $this->state->get('field.field.deleted') ?: array();
$deleted_storages = $this->state->get('field.storage.deleted') ?: array();
$deleted_fields = $this->state->get('field.field.deleted') ?: [];
$deleted_storages = $this->state->get('field.storage.deleted') ?: [];
foreach ($deleted_fields as $id => $config) {
// If the field storage itself is deleted, inject it directly in the field.
if (isset($deleted_storages[$config['field_storage_uuid']])) {
@@ -131,7 +131,7 @@ class FieldConfigStorage extends FieldConfigStorageBase {
}
// Collect matching fields.
$matching_fields = array();
$matching_fields = [];
foreach ($fields as $field) {
// Some conditions are checked against the field storage.
$field_storage = $field->getFieldStorageDefinition();
@@ -0,0 +1,33 @@
<?php
namespace Drupal\field;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Defines the access control handler for the field storage config entity type.
*
* @see \Drupal\field\Entity\FieldStorageConfig
*/
class FieldStorageConfigAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** \Drupal\field\FieldStorageConfigInterface $entity */
if ($operation === 'delete') {
if ($entity->isLocked()) {
return AccessResult::forbidden()->addCacheableDependency($entity);
}
else {
return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields')->addCacheableDependency($entity);
}
}
return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields');
}
}
@@ -64,7 +64,7 @@ class FieldStorageConfigStorage extends ConfigEntityStorage {
* The module handler.
* @param \Drupal\Core\State\StateInterface $state
* The state key value store.
* @param \Drupal\Component\Plugin\PluginManagerInterface\FieldTypePluginManagerInterface
* @param \Drupal\Component\Plugin\PluginManagerInterface\FieldTypePluginManagerInterface $field_type_manager
* The field type plugin manager.
*/
public function __construct(EntityTypeInterface $entity_type, ConfigFactoryInterface $config_factory, UuidInterface $uuid_service, LanguageManagerInterface $language_manager, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, StateInterface $state, FieldTypePluginManagerInterface $field_type_manager) {
@@ -94,13 +94,13 @@ class FieldStorageConfigStorage extends ConfigEntityStorage {
/**
* {@inheritdoc}
*/
public function loadByProperties(array $conditions = array()) {
public function loadByProperties(array $conditions = []) {
// Include deleted fields if specified in the $conditions parameters.
$include_deleted = isset($conditions['include_deleted']) ? $conditions['include_deleted'] : FALSE;
unset($conditions['include_deleted']);
/** @var \Drupal\field\FieldStorageConfigInterface[] $storages */
$storages = array();
$storages = [];
// Get field storages living in configuration. If we are explicitly looking
// for deleted storages only, this can be skipped, because they will be
@@ -109,7 +109,7 @@ class FieldStorageConfigStorage extends ConfigEntityStorage {
if (isset($conditions['entity_type']) && isset($conditions['field_name'])) {
// Optimize for the most frequent case where we do have a specific ID.
$id = $conditions['entity_type'] . $conditions['field_name'];
$storages = $this->loadMultiple(array($id));
$storages = $this->loadMultiple([$id]);
}
else {
// No specific ID, we need to examine all existing storages.
@@ -119,14 +119,14 @@ class FieldStorageConfigStorage extends ConfigEntityStorage {
// Merge deleted field storages (living in state) if needed.
if ($include_deleted || !empty($conditions['deleted'])) {
$deleted_storages = $this->state->get('field.storage.deleted') ?: array();
$deleted_storages = $this->state->get('field.storage.deleted') ?: [];
foreach ($deleted_storages as $id => $config) {
$storages[$id] = $this->create($config);
}
}
// Collect matching fields.
$matches = array();
$matches = [];
foreach ($storages as $field) {
foreach ($conditions as $key => $value) {
// Extract the actual value against which the condition is checked.
@@ -150,8 +150,12 @@ class FieldStorageConfigStorage extends ConfigEntityStorage {
* {@inheritdoc}
*/
protected function mapFromStorageRecords(array $records) {
foreach ($records as &$record) {
foreach ($records as $id => &$record) {
$class = $this->fieldTypeManager->getPluginClass($record['type']);
if (empty($class)) {
$config_id = $this->getPrefix() . $id;
throw new \RuntimeException("Unable to determine class for field type '{$record['type']}' found in the '$config_id' configuration");
}
$record['settings'] = $class::storageSettingsFromConfigData($record['settings']);
}
return parent::mapFromStorageRecords($records);
@@ -3,12 +3,13 @@
namespace Drupal\field\Plugin\migrate\process;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\process\StaticMap;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface;
use Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -21,10 +22,17 @@ class FieldType extends StaticMap implements ContainerFactoryPluginInterface {
/**
* The cckfield plugin manager.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
* @var \Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface
*/
protected $cckPluginManager;
/**
* The field plugin manager.
*
* @var \Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface
*/
protected $fieldPluginManager;
/**
* The migration object.
*
@@ -41,14 +49,17 @@ class FieldType extends StaticMap implements ContainerFactoryPluginInterface {
* The plugin ID.
* @param mixed $plugin_definition
* The plugin definition.
* @param \Drupal\Component\Plugin\PluginManagerInterface $cck_plugin_manager
* @param \Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface $cck_plugin_manager
* The cckfield plugin manager.
* @param \Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface $field_plugin_manager
* The field plugin manager.
* @param \Drupal\migrate\Plugin\MigrationInterface $migration
* The migration being run.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, PluginManagerInterface $cck_plugin_manager, MigrationInterface $migration = NULL) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrateCckFieldPluginManagerInterface $cck_plugin_manager, MigrateFieldPluginManagerInterface $field_plugin_manager, MigrationInterface $migration = NULL) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->cckPluginManager = $cck_plugin_manager;
$this->fieldPluginManager = $field_plugin_manager;
$this->migration = $migration;
}
@@ -61,6 +72,7 @@ class FieldType extends StaticMap implements ContainerFactoryPluginInterface {
$plugin_id,
$plugin_definition,
$container->get('plugin.manager.migrate.cckfield'),
$container->get('plugin.manager.migrate.field'),
$migration
);
}
@@ -70,12 +82,18 @@ class FieldType extends StaticMap implements ContainerFactoryPluginInterface {
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$field_type = is_array($value) ? $value[0] : $value;
try {
return $this->cckPluginManager->createInstance($field_type, [], $this->migration)->getFieldType($row);
$plugin_id = $this->fieldPluginManager->getPluginIdFromFieldType($field_type, [], $this->migration);
return $this->fieldPluginManager->createInstance($plugin_id, [], $this->migration)->getFieldType($row);
}
catch (PluginNotFoundException $e) {
return parent::transform($value, $migrate_executable, $row, $destination_property);
try {
$plugin_id = $this->cckPluginManager->getPluginIdFromFieldType($field_type, [], $this->migration);
return $this->cckPluginManager->createInstance($plugin_id, [], $this->migration)->getFieldType($row);
}
catch (PluginNotFoundException $e) {
return parent::transform($value, $migrate_executable, $row, $destination_property);
}
}
}
@@ -26,7 +26,7 @@ class FieldFormatterSettingsDefaults extends ProcessPluginBase {
if (isset($value[1])) {
$module = $row->getSourceProperty('module');
if ($module === 'date') {
$value = array('format_type' => 'fallback');
$value = ['format_type' => 'fallback'];
}
elseif ($module === 'number') {
// We have to do the lookup here in the process plugin because for
@@ -35,7 +35,7 @@ class FieldFormatterSettingsDefaults extends ProcessPluginBase {
return $this->numberSettings($row->getDestinationProperty('options/type'), $value[1]);
}
else {
$value = array();
$value = [];
}
}
return $value;
@@ -20,7 +20,7 @@ class FieldInstanceDefaults extends ProcessPluginBase {
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
list($widget_type, $widget_settings) = $value;
$default = array();
$default = [];
switch ($widget_type) {
case 'text_textfield':
@@ -58,7 +58,7 @@ class FieldInstanceDefaults extends ProcessPluginBase {
break;
}
if (!empty($default)) {
$default = array($default);
$default = [$default];
}
return $default;
}
@@ -20,7 +20,7 @@ class FieldInstanceSettings extends ProcessPluginBase {
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
list($widget_type, $widget_settings, $field_settings) = $value;
$settings = array();
$settings = [];
switch ($widget_type) {
case 'number':
$settings['min'] = $field_settings['min'];
@@ -33,7 +33,7 @@ class FieldInstanceSettings extends ProcessPluginBase {
// $settings['url'] = $widget_settings['default_value'][0]['url'];
// D6 has optional, required, value and none. D8 only has disabled (0)
// optional (1) and required (2).
$map = array('disabled' => 0, 'optional' => 1, 'required' => 2);
$map = ['disabled' => 0, 'optional' => 1, 'required' => 2];
$settings['title'] = $map[$field_settings['title']];
break;
@@ -41,41 +41,41 @@ class FieldInstanceWidgetSettings extends ProcessPluginBase {
$size = isset($widget_settings['size']) ? $widget_settings['size'] : 60;
$rows = isset($widget_settings['rows']) ? $widget_settings['rows'] : 5;
$settings = array(
'text_textfield' => array(
$settings = [
'text_textfield' => [
'size' => $size,
'placeholder' => '',
),
'text_textarea' => array(
],
'text_textarea' => [
'rows' => $rows,
'placeholder' => '',
),
'number' => array(
],
'number' => [
'placeholder' => '',
),
'email_textfield' => array(
],
'email_textfield' => [
'placeholder' => '',
),
'link' => array(
],
'link' => [
'placeholder_url' => '',
'placeholder_title' => '',
),
'filefield_widget' => array(
],
'filefield_widget' => [
'progress_indicator' => $progress,
),
'imagefield_widget' => array(
],
'imagefield_widget' => [
'progress_indicator' => $progress,
'preview_image_style' => 'thumbnail',
),
'optionwidgets_onoff' => array(
],
'optionwidgets_onoff' => [
'display_label' => FALSE,
),
'phone_textfield' => array(
],
'phone_textfield' => [
'placeholder' => '',
),
);
],
];
return isset($settings[$widget_type]) ? $settings[$widget_type] : array();
return isset($settings[$widget_type]) ? $settings[$widget_type] : [];
}
}
@@ -21,22 +21,29 @@ class FieldSettings extends ProcessPluginBase {
* Get the field default/mapped settings.
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
list($field_type, $global_settings) = $value;
return $this->getSettings($field_type, $global_settings);
// To maintain backwards compatibility, ensure that $value contains at least
// three elements.
if (count($value) == 2) {
$value[] = NULL;
}
list($field_type, $global_settings, $original_field_type) = $value;
return $this->getSettings($field_type, $global_settings, $original_field_type);
}
/**
* Merge the default D8 and specified D6 settings.
*
* @param string $field_type
* The field type.
* The destination field type.
* @param array $global_settings
* The field settings.
* @param string $original_field_type
* (optional) The original field type before migration.
*
* @return array
* A valid array of settings.
*/
public function getSettings($field_type, $global_settings) {
public function getSettings($field_type, $global_settings, $original_field_type = NULL) {
$max_length = isset($global_settings['max_length']) ? $global_settings['max_length'] : '';
$max_length = empty($max_length) ? 255 : $max_length;
$allowed_values = [];
@@ -59,26 +66,31 @@ class FieldSettings extends ProcessPluginBase {
}
}
$settings = array(
'text' => array(
$settings = [
'text' => [
'max_length' => $max_length,
),
'datetime' => array('datetime_type' => 'datetime'),
'list_string' => array(
],
'datetime' => ['datetime_type' => 'datetime'],
'list_string' => [
'allowed_values' => $allowed_values,
),
'list_integer' => array(
],
'list_integer' => [
'allowed_values' => $allowed_values,
),
'list_float' => array(
],
'list_float' => [
'allowed_values' => $allowed_values,
),
'boolean' => array(
],
'boolean' => [
'allowed_values' => $allowed_values,
),
);
],
];
return isset($settings[$field_type]) ? $settings[$field_type] : array();
if ($original_field_type == 'userreference') {
return ['target_type' => 'user'];
}
else {
return isset($settings[$field_type]) ? $settings[$field_type] : [];
}
}
}
@@ -20,7 +20,7 @@ class FieldInstanceDefaults extends ProcessPluginBase {
list($default_value, $widget_settings) = $value;
$widget_type = $widget_settings['type'];
$default = array();
$default = [];
foreach ($default_value as $item) {
switch ($widget_type) {
@@ -17,19 +17,48 @@ class FieldInstanceSettings extends ProcessPluginBase {
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
list($instance_settings, $widget_settings) = $value;
list($instance_settings, $widget_settings, $field_settings) = $value;
$widget_type = $widget_settings['type'];
// Get entityreference handler settings from source field configuration.
if ($row->getSourceProperty('type') == "entityreference") {
$instance_settings['handler'] = 'default:' . $field_settings['target_type'];
// Transform the sort settings to D8 structure.
$sort = [
'field' => '_none',
'direction' => 'ASC',
];
if (!empty(array_filter($field_settings['handler_settings']['sort']))) {
if ($field_settings['handler_settings']['sort']['type'] == "property") {
$sort = [
'field' => $field_settings['handler_settings']['sort']['property'],
'direction' => $field_settings['handler_settings']['sort']['direction'],
];
}
elseif ($field_settings['handler_settings']['sort']['type'] == "field") {
$sort = [
'field' => $field_settings['handler_settings']['sort']['field'],
'direction' => $field_settings['handler_settings']['sort']['direction'],
];
}
}
if (empty($field_settings['handler_settings']['target_bundles'])) {
$field_settings['handler_settings']['target_bundles'] = NULL;
}
$field_settings['handler_settings']['sort'] = $sort;
$instance_settings['handler_settings'] = $field_settings['handler_settings'];
}
switch ($widget_type) {
case 'image_image':
$settings = $instance_settings;
$settings['default_image'] = array(
$settings['default_image'] = [
'alt' => '',
'title' => '',
'width' => NULL,
'height' => NULL,
'uuid' => '',
);
];
break;
default:
@@ -22,7 +22,7 @@ class FieldSettings extends ProcessPluginBase {
switch ($row->getSourceProperty('type')) {
case 'image':
if (!is_array($value['default_image'])) {
$value['default_image'] = array('uuid' => '');
$value['default_image'] = ['uuid' => ''];
}
break;
@@ -20,7 +20,7 @@ class Field extends DrupalSqlBase {
*/
public function query() {
$query = $this->select('content_node_field', 'cnf')
->fields('cnf', array(
->fields('cnf', [
'field_name',
'type',
'global_settings',
@@ -31,7 +31,7 @@ class Field extends DrupalSqlBase {
'db_columns',
'active',
'locked',
))
])
->distinct();
// Only import fields which are actually being used.
$query->innerJoin('content_node_field_instance', 'cnfi', 'cnfi.field_name = cnf.field_name');
@@ -43,7 +43,7 @@ class Field extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'field_name' => $this->t('Field name'),
'type' => $this->t('Type (text, integer, ....)'),
'widget_type' => $this->t('An instance-specific widget type'),
@@ -55,7 +55,7 @@ class Field extends DrupalSqlBase {
'db_columns' => $this->t('DB Columns'),
'active' => $this->t('Active'),
'locked' => $this->t('Locked'),
);
];
}
/**
@@ -96,10 +96,10 @@ class Field extends DrupalSqlBase {
* {@inheritdoc}
*/
public function getIds() {
$ids['field_name'] = array(
$ids['field_name'] = [
'type' => 'string',
'alias' => 'cnf',
);
];
return $ids;
}
@@ -33,7 +33,7 @@ class FieldInstance extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'field_name' => $this->t('The machine name of field.'),
'type_name' => $this->t('Content type where this field is in use.'),
'weight' => $this->t('Weight.'),
@@ -45,7 +45,7 @@ class FieldInstance extends DrupalSqlBase {
'widget_module' => $this->t('Module that implements widget.'),
'widget_active' => $this->t('Status of widget'),
'module' => $this->t('The module that provides the field.'),
);
];
}
/**
@@ -66,15 +66,15 @@ class FieldInstance extends DrupalSqlBase {
* {@inheritdoc}
*/
public function getIds() {
$ids = array(
'field_name' => array(
$ids = [
'field_name' => [
'type' => 'string',
'alias' => 'cnfi',
),
'type_name' => array(
],
'type_name' => [
'type' => 'string',
),
);
],
];
return $ids;
}
@@ -18,11 +18,9 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
* {@inheritdoc}
*/
protected function initializeIterator() {
$rows = array();
$rows = [];
$result = $this->prepareQuery()->execute();
while ($field_row = $result->fetchAssoc()) {
$field_row['display_settings'] = unserialize($field_row['display_settings']);
$field_row['widget_settings'] = unserialize($field_row['widget_settings']);
$bundle = $field_row['type_name'];
$field_name = $field_row['field_name'];
@@ -34,7 +32,8 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
$rows[$index]['module'] = $field_row['module'];
$rows[$index]['weight'] = $field_row['weight'];
$rows[$index]['widget_type'] = $field_row['widget_type'];
$rows[$index]['widget_settings'] = $field_row['widget_settings'];
$rows[$index]['widget_settings'] = unserialize($field_row['widget_settings']);
$rows[$index]['display_settings'] = unserialize($field_row['display_settings']);
}
return new \ArrayIterator($rows);
@@ -45,7 +44,7 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
*/
public function query() {
$query = $this->select('content_node_field_instance', 'cnfi')
->fields('cnfi', array(
->fields('cnfi', [
'field_name',
'type_name',
'weight',
@@ -56,11 +55,11 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
'description',
'widget_module',
'widget_active',
))
->fields('cnf', array(
])
->fields('cnf', [
'type',
'module',
));
]);
$query->join('content_node_field', 'cnf', 'cnfi.field_name = cnf.field_name');
$query->orderBy('cnfi.weight');
@@ -71,7 +70,7 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'field_name' => $this->t('The machine name of field.'),
'type_name' => $this->t('Content type where this field is used.'),
'weight' => $this->t('Weight.'),
@@ -82,7 +81,7 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
'description' => $this->t('A description of field.'),
'widget_module' => $this->t('Module that implements widget.'),
'widget_active' => $this->t('Status of widget'),
);
];
}
/**
@@ -18,7 +18,7 @@ class FieldInstancePerViewMode extends ViewModeBase {
* {@inheritdoc}
*/
protected function initializeIterator() {
$rows = array();
$rows = [];
$result = $this->prepareQuery()->execute();
while ($field_row = $result->fetchAssoc()) {
// These are added to every view mode row.
@@ -28,7 +28,10 @@ class FieldInstancePerViewMode extends ViewModeBase {
$field_name = $field_row['field_name'];
foreach ($this->getViewModes() as $view_mode) {
if (isset($field_row['display_settings'][$view_mode]) && empty($field_row['display_settings'][$view_mode]['exclude'])) {
// Append to the return value if the row has display settings for this
// view mode and the view mode is neither hidden nor excluded.
// @see \Drupal\node\Plugin\migrate\source\d6\ViewMode::initializeIterator()
if (isset($field_row['display_settings'][$view_mode]) && $field_row['display_settings'][$view_mode]['format'] != 'hidden' && empty($field_row['display_settings'][$view_mode]['exclude'])) {
$index = $view_mode . "." . $bundle . "." . $field_name;
$rows[$index]['entity_type'] = 'node';
$rows[$index]['view_mode'] = $view_mode;
@@ -52,18 +55,18 @@ class FieldInstancePerViewMode extends ViewModeBase {
*/
public function query() {
$query = $this->select('content_node_field_instance', 'cnfi')
->fields('cnfi', array(
->fields('cnfi', [
'field_name',
'type_name',
'weight',
'label',
'display_settings',
'widget_settings',
))
->fields('cnf', array(
])
->fields('cnf', [
'type',
'module',
));
]);
$query->join('content_node_field', 'cnf', 'cnfi.field_name = cnf.field_name');
$query->orderBy('cnfi.weight');
@@ -74,7 +77,7 @@ class FieldInstancePerViewMode extends ViewModeBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'field_name' => $this->t('The machine name of field.'),
'type_name' => $this->t('Content type where this field is used.'),
'weight' => $this->t('Weight.'),
@@ -85,7 +88,7 @@ class FieldInstancePerViewMode extends ViewModeBase {
'description' => $this->t('A description of field.'),
'widget_module' => $this->t('Module that implements widget.'),
'widget_active' => $this->t('Status of widget'),
);
];
}
/**
@@ -21,7 +21,7 @@ class Field extends DrupalSqlBase {
$query = $this->select('field_config', 'fc')
->distinct()
->fields('fc')
->fields('fci', array('entity_type'))
->fields('fci', ['entity_type'])
->condition('fc.active', 1)
->condition('fc.deleted', 0)
->condition('fc.storage_active', 1);
@@ -34,7 +34,7 @@ class Field extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'field_name' => $this->t('The name of this field.'),
'type' => $this->t('The type of this field.'),
'module' => $this->t('The module that implements the field type.'),
@@ -42,7 +42,7 @@ class Field extends DrupalSqlBase {
'locked' => $this->t('Locked'),
'cardinality' => $this->t('Cardinality'),
'translatable' => $this->t('Translatable'),
);
];
}
/**
@@ -59,16 +59,16 @@ class Field extends DrupalSqlBase {
* {@inheritdoc}
*/
public function getIds() {
return array(
'field_name' => array(
return [
'field_name' => [
'type' => 'string',
'alias' => 'fc',
),
'entity_type' => array(
],
'entity_type' => [
'type' => 'string',
'alias' => 'fci',
),
);
],
];
}
}
@@ -25,9 +25,10 @@ class FieldInstance extends DrupalSqlBase {
->condition('fc.active', 1)
->condition('fc.deleted', 0)
->condition('fc.storage_active', 1)
->fields('fc', array('type'));
->fields('fc', ['type']);
$query->innerJoin('field_config', 'fc', 'fci.field_id = fc.id');
$query->addField('fc', 'data', 'field_data');
// Optionally filter by entity type and bundle.
if (isset($this->configuration['entity_type'])) {
@@ -45,7 +46,7 @@ class FieldInstance extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'field_name' => $this->t('The machine name of field.'),
'entity_type' => $this->t('The entity type.'),
'bundle' => $this->t('The entity bundle.'),
@@ -53,7 +54,8 @@ class FieldInstance extends DrupalSqlBase {
'instance_settings' => $this->t('Field instance settings.'),
'widget_settings' => $this->t('Widget settings.'),
'display_settings' => $this->t('Display settings.'),
);
'field_settings' => $this->t('Field settings.'),
];
}
/**
@@ -66,7 +68,7 @@ class FieldInstance extends DrupalSqlBase {
$row->setSourceProperty('description', $data['description']);
$row->setSourceProperty('required', $data['required']);
$default_value = !empty($data['default_value']) ? $data['default_value'] : array();
$default_value = !empty($data['default_value']) ? $data['default_value'] : [];
if ($data['widget']['type'] == 'email_textfield' && $default_value) {
$default_value[0]['value'] = $default_value[0]['email'];
unset($default_value[0]['email']);
@@ -81,6 +83,28 @@ class FieldInstance extends DrupalSqlBase {
// This is for parity with the d6_field_instance plugin.
$row->setSourceProperty('widget_type', $data['widget']['type']);
$field_data = unserialize($row->getSourceProperty('field_data'));
$row->setSourceProperty('field_settings', $field_data['settings']);
$translatable = FALSE;
if ($row->getSourceProperty('entity_type') == 'node') {
// language_content_type_[bundle] may be
// - 0: no language support
// - 1: language assignment support
// - 2: node translation support
// - 4: entity translation support
if ($this->variableGet('language_content_type_' . $row->getSourceProperty('bundle'), 0) == 2) {
$translatable = TRUE;
}
}
else {
// This is not a node entity. Get the translatable value from the source
// field_config table.
$data = unserialize($row->getSourceProperty('field_data'));
$translatable = $data['translatable'];
}
$row->setSourceProperty('translatable', $translatable);
return parent::prepareRow($row);
}
@@ -88,20 +112,20 @@ class FieldInstance extends DrupalSqlBase {
* {@inheritdoc}
*/
public function getIds() {
return array(
'entity_type' => array(
return [
'entity_type' => [
'type' => 'string',
'alias' => 'fci',
),
'bundle' => array(
],
'bundle' => [
'type' => 'string',
'alias' => 'fci',
),
'field_name' => array(
],
'field_name' => [
'type' => 'string',
'alias' => 'fci',
),
);
],
];
}
}
@@ -19,16 +19,16 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
*/
public function query() {
$query = $this->select('field_config_instance', 'fci')
->fields('fci', array(
->fields('fci', [
'field_name',
'bundle',
'data',
'entity_type'
))
->fields('fc', array(
])
->fields('fc', [
'type',
'module',
));
]);
$query->join('field_config', 'fc', 'fci.field_id = fc.id');
return $query;
}
@@ -47,27 +47,27 @@ class FieldInstancePerFormDisplay extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'field_name' => $this->t('The machine name of field.'),
'bundle' => $this->t('Content type where this field is used.'),
'data' => $this->t('Field configuration data.'),
'entity_type' => $this->t('The entity type.'),
);
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
return array(
'bundle' => array(
return [
'bundle' => [
'type' => 'string',
),
'field_name' => array(
],
'field_name' => [
'type' => 'string',
'alias' => 'fci',
),
);
],
];
}
}
@@ -18,14 +18,21 @@ class FieldInstancePerViewMode extends DrupalSqlBase {
* {@inheritdoc}
*/
protected function initializeIterator() {
$rows = array();
$rows = [];
$result = $this->prepareQuery()->execute();
foreach ($result as $field_instance) {
$data = unserialize($field_instance['data']);
// We don't need to include the serialized data in the returned rows.
unset($field_instance['data']);
foreach ($data['display'] as $view_mode => $info) {
$rows[] = array_merge($field_instance, $info, array('view_mode' => $view_mode));
// Rename type to formatter_type in the info array.
$info['formatter_type'] = $info['type'];
unset($info['type']);
$rows[] = array_merge($field_instance, $info, [
'view_mode' => $view_mode,
]);
}
}
return new \ArrayIterator($rows);
@@ -35,45 +42,49 @@ class FieldInstancePerViewMode extends DrupalSqlBase {
* {@inheritdoc}
*/
public function query() {
return $this->select('field_config_instance', 'fci')
->fields('fci', array('entity_type', 'bundle', 'field_name', 'data'));
$query = $this->select('field_config_instance', 'fci')
->fields('fci', ['entity_type', 'bundle', 'field_name', 'data'])
->fields('fc', ['type']);
$query->join('field_config', 'fc', 'fc.field_name = fci.field_name');
return $query;
}
/**
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'entity_type' => $this->t('The entity type ID.'),
'bundle' => $this->t('The bundle ID.'),
'field_name' => $this->t('Machine name of the field.'),
'view_mode' => $this->t('The original machine name of the view mode.'),
'label' => $this->t('The display label of the field.'),
'type' => $this->t('The formatter ID.'),
'type' => $this->t('The field ID.'),
'formatter_type' => $this->t('The formatter ID.'),
'settings' => $this->t('Array of formatter-specific settings.'),
'module' => $this->t('The module providing the formatter.'),
'weight' => $this->t('Display weight of the field.'),
);
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
return array(
'entity_type' => array(
return [
'entity_type' => [
'type' => 'string',
),
'bundle' => array(
],
'bundle' => [
'type' => 'string',
),
'view_mode' => array(
],
'view_mode' => [
'type' => 'string',
),
'field_name' => array(
],
'field_name' => [
'type' => 'string',
),
);
],
];
}
/**
@@ -3,6 +3,7 @@
namespace Drupal\field\Tests\Boolean;
use Drupal\Component\Utility\Unicode;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\simpletest\WebTestBase;
@@ -19,7 +20,12 @@ class BooleanFieldTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('entity_test', 'field_ui', 'options');
public static $modules = [
'entity_test',
'field_ui',
'options',
'field_test_boolean_access_denied',
];
/**
* A field to use in this test class.
@@ -41,101 +47,102 @@ class BooleanFieldTest extends WebTestBase {
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser(array(
$this->drupalLogin($this->drupalCreateUser([
'view test entity',
'administer entity_test content',
'administer entity_test form display',
'administer entity_test fields',
)));
]));
}
/**
* Tests boolean field.
*/
function testBooleanField() {
public function testBooleanField() {
$on = $this->randomMachineName();
$off = $this->randomMachineName();
$label = $this->randomMachineName();
// Create a field with settings to validate.
$field_name = Unicode::strtolower($this->randomMachineName());
$this->fieldStorage = FieldStorageConfig::create(array(
$this->fieldStorage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'boolean',
));
]);
$this->fieldStorage->save();
$this->field = FieldConfig::create(array(
$this->field = FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'label' => $label,
'required' => TRUE,
'settings' => array(
'settings' => [
'on_label' => $on,
'off_label' => $off,
),
));
],
]);
$this->field->save();
// Create a form display for the default form mode.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'boolean_checkbox',
))
])
->save();
// Create a display for the full view mode.
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'boolean',
))
])
->save();
// Display creation form.
$this->drupalGet('entity_test/add');
$this->assertFieldByName("{$field_name}[value]", '', 'Widget found.');
$this->assertRaw($on);
$this->assertText($this->field->label(), 'Uses field label by default.');
$this->assertNoRaw($on, 'Does not use the "On" label.');
// Submit and ensure it is accepted.
$edit = array(
$edit = [
"{$field_name}[value]" => 1,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
// Verify that boolean value is displayed.
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full');
$content = $display->build($entity);
$this->setRawContent(\Drupal::service('renderer')->renderRoot($content));
$this->assertRaw('<div class="field__item">' . $on . '</div>');
// Test if we can change the on label.
$on = $this->randomMachineName();
$edit = array(
'settings[on_label]' => $on,
);
$this->drupalPostForm('entity_test/structure/entity_test/fields/entity_test.entity_test.' . $field_name, $edit, t('Save settings'));
// Check if we see the updated labels in the creation form.
$this->drupalGet('entity_test/add');
$this->assertRaw($on);
// Test the display_label option.
// Test with "On" label option.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'boolean_checkbox',
'settings' => array(
'display_label' => TRUE,
)
))
'settings' => [
'display_label' => FALSE,
]
])
->save();
$this->drupalGet('entity_test/add');
$this->assertFieldByName("{$field_name}[value]", '', 'Widget found.');
$this->assertNoRaw($on);
$this->assertText($this->field->label());
$this->assertRaw($on);
$this->assertNoText($this->field->label());
// Test if we can change the on label.
$on = $this->randomMachineName();
$edit = [
'settings[on_label]' => $on,
];
$this->drupalPostForm('entity_test/structure/entity_test/fields/entity_test.entity_test.' . $field_name, $edit, t('Save settings'));
// Check if we see the updated labels in the creation form.
$this->drupalGet('entity_test/add');
$this->assertRaw($on);
// Go to the form display page and check if the default settings works as
// expected.
@@ -143,7 +150,7 @@ class BooleanFieldTest extends WebTestBase {
$this->drupalGet($fieldEditUrl);
// Click on the widget settings button to open the widget settings form.
$this->drupalPostAjaxForm(NULL, array(), $field_name . "_settings_edit");
$this->drupalPostAjaxForm(NULL, [], $field_name . "_settings_edit");
$this->assertText(
'Use field label instead of the "On label" as label',
@@ -151,7 +158,7 @@ class BooleanFieldTest extends WebTestBase {
);
// Enable setting.
$edit = array('fields[' . $field_name . '][settings_edit_form][settings][display_label]' => 1);
$edit = ['fields[' . $field_name . '][settings_edit_form][settings][display_label]' => 1];
$this->drupalPostAjaxForm(NULL, $edit, $field_name . "_plugin_settings_update");
$this->drupalPostForm(NULL, NULL, 'Save');
@@ -160,7 +167,7 @@ class BooleanFieldTest extends WebTestBase {
$this->drupalGet($fieldEditUrl);
$this->assertText('Use field label: Yes', 'Checking the display settings checkbox updated the value.');
$this->drupalPostAjaxForm(NULL, array(), $field_name . "_settings_edit");
$this->drupalPostAjaxForm(NULL, [], $field_name . "_settings_edit");
$this->assertText(
'Use field label instead of the "On label" as label',
t('Display setting checkbox is available')
@@ -177,4 +184,66 @@ class BooleanFieldTest extends WebTestBase {
$this->assertFieldById('edit-settings-off-label', $off);
}
/**
* Test field access.
*/
public function testFormAccess() {
$on = 'boolean_on';
$off = 'boolean_off';
$label = 'boolean_label';
$field_name = 'boolean_name';
$this->fieldStorage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'boolean',
]);
$this->fieldStorage->save();
$this->field = FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'label' => $label,
'settings' => [
'on_label' => $on,
'off_label' => $off,
],
]);
$this->field->save();
// Create a form display for the default form mode.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, [
'type' => 'boolean_checkbox',
])
->save();
// Create a display for the full view mode.
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, [
'type' => 'boolean',
])
->save();
// Display creation form.
$this->drupalGet('entity_test/add');
$this->assertFieldByName("{$field_name}[value]");
// Should be posted OK.
$this->drupalPostForm(NULL, [], t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
// Tell the test module to disable access to the field.
\Drupal::state()->set('field.test_boolean_field_access_field', $field_name);
$this->drupalGet('entity_test/add');
// Field should not be there anymore.
$this->assertNoFieldByName("{$field_name}[value]");
// Should still be able to post the form.
$this->drupalPostForm(NULL, [], t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
}
}
@@ -44,10 +44,10 @@ class BooleanFormatterSettingsTest extends WebTestBase {
// Create a content type. Use Node because it has Field UI pages that work.
$type_name = Unicode::strtolower($this->randomMachineName(8)) . '_test';
$type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name));
$type = $this->drupalCreateContentType(['name' => $type_name, 'type' => $type_name]);
$this->bundle = $type->id();
$admin_user = $this->drupalCreateUser(array('access content', 'administer content types', 'administer node fields', 'administer node display', 'bypass node access', 'administer nodes'));
$admin_user = $this->drupalCreateUser(['access content', 'administer content types', 'administer node fields', 'administer node display', 'bypass node access', 'administer nodes']);
$this->drupalLogin($admin_user);
$this->fieldName = Unicode::strtolower($this->randomMachineName(8));
@@ -77,18 +77,18 @@ class BooleanFormatterSettingsTest extends WebTestBase {
/**
* Tests the formatter settings page for the Boolean formatter.
*/
function testBooleanFormatterSettings() {
public function testBooleanFormatterSettings() {
// List the options we expect to see on the settings form. Omit the one
// with the Unicode check/x characters, which does not appear to work
// well in WebTestBase.
$options = array(
$options = [
'Yes / No',
'True / False',
'On / Off',
'Enabled / Disabled',
'1 / 0',
'Custom',
);
];
// Define what the "default" option should look like, depending on the
// field settings.
@@ -96,29 +96,29 @@ class BooleanFormatterSettingsTest extends WebTestBase {
// For several different values of the field settings, test that the
// options, including default, are shown correctly.
$settings = array(
array('Yes', 'No'),
array('On', 'Off'),
array('TRUE', 'FALSE'),
);
$settings = [
['Yes', 'No'],
['On', 'Off'],
['TRUE', 'FALSE'],
];
foreach ($settings as $values) {
// Set up the field settings.
$this->drupalGet('admin/structure/types/manage/' . $this->bundle . '/fields/node.' . $this->bundle . '.' . $this->fieldName);
$this->drupalPostForm(NULL, array(
$this->drupalPostForm(NULL, [
'settings[on_label]' => $values[0],
'settings[off_label]' => $values[1],
), 'Save settings');
], 'Save settings');
// Open the Manage Display page and trigger the field settings form.
$this->drupalGet('admin/structure/types/manage/' . $this->bundle . '/display');
$this->drupalPostAjaxForm(NULL, array(), $this->fieldName . '_settings_edit');
$this->drupalPostAjaxForm(NULL, [], $this->fieldName . '_settings_edit');
// Test that the settings options are present in the correct format.
foreach ($options as $string) {
$this->assertText($string);
}
$this->assertText(SafeMarkup::format($default, array('@on' => $values[0], '@off' => $values[1])));
$this->assertText(SafeMarkup::format($default, ['@on' => $values[0], '@off' => $values[1]]));
}
foreach ($settings as $values) {
@@ -3,6 +3,7 @@
namespace Drupal\field\Tests\Email;
use Drupal\Component\Utility\Unicode;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\simpletest\WebTestBase;
use Drupal\field\Entity\FieldStorageConfig;
@@ -19,7 +20,7 @@ class EmailFieldTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('node', 'entity_test', 'field_ui');
public static $modules = ['node', 'entity_test', 'field_ui'];
/**
* A field storage to use in this test class.
@@ -38,24 +39,24 @@ class EmailFieldTest extends WebTestBase {
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser(array(
$this->drupalLogin($this->drupalCreateUser([
'view test entity',
'administer entity_test content',
'administer content types',
)));
]));
}
/**
* Tests email field.
*/
function testEmailField() {
public function testEmailField() {
// Create a field with settings to validate.
$field_name = Unicode::strtolower($this->randomMachineName());
$this->fieldStorage = FieldStorageConfig::create(array(
$this->fieldStorage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'email',
));
]);
$this->fieldStorage->save();
$this->field = FieldConfig::create([
'field_storage' => $this->fieldStorage,
@@ -65,18 +66,18 @@ class EmailFieldTest extends WebTestBase {
// Create a form display for the default form mode.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'email_default',
'settings' => array(
'settings' => [
'placeholder' => 'example@example.com',
),
))
],
])
->save();
// Create a display for the full view mode.
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'email_mailto',
))
])
->save();
// Display creation form.
@@ -86,17 +87,17 @@ class EmailFieldTest extends WebTestBase {
// Submit a valid email address and ensure it is accepted.
$value = 'test@example.com';
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
$this->assertRaw($value);
// Verify that a mailto link is displayed.
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full');
$content = $display->build($entity);
$this->setRawContent(\Drupal::service('renderer')->renderRoot($content));
@@ -46,18 +46,18 @@ class EntityReferenceAdminTest extends WebTestBase {
// Create a content type, with underscores.
$type_name = strtolower($this->randomMachineName(8)) . '_test';
$type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name));
$type = $this->drupalCreateContentType(['name' => $type_name, 'type' => $type_name]);
$this->type = $type->id();
// Create test user.
$admin_user = $this->drupalCreateUser(array(
$admin_user = $this->drupalCreateUser([
'access content',
'administer node fields',
'administer node display',
'administer views',
'create ' . $type_name . ' content',
'edit own ' . $type_name . ' content',
));
]);
$this->drupalLogin($admin_user);
}
@@ -74,11 +74,11 @@ class EntityReferenceAdminTest extends WebTestBase {
$this->assertOption('edit-new-storage-type', 'field_ui:entity_reference:node');
$this->assertOption('edit-new-storage-type', 'field_ui:entity_reference:user');
$this->drupalPostForm(NULL, array(
$this->drupalPostForm(NULL, [
'label' => 'Test label',
'field_name' => 'test',
'new_storage_type' => 'entity_reference',
), t('Save and continue'));
], t('Save and continue'));
// Node should be selected by default.
$this->assertFieldByName('settings[target_type]', 'node');
@@ -87,14 +87,14 @@ class EntityReferenceAdminTest extends WebTestBase {
$this->assertFieldSelectOptions('settings[target_type]', array_keys(\Drupal::entityManager()->getDefinitions()));
// Second step: 'Field settings' form.
$this->drupalPostForm(NULL, array(), t('Save field settings'));
$this->drupalPostForm(NULL, [], t('Save field settings'));
// The base handler should be selected by default.
$this->assertFieldByName('settings[handler]', 'default:node');
// The base handler settings should be displayed.
$entity_type_id = 'node';
$bundles = entity_get_bundles($entity_type_id);
$bundles = $this->container->get('entity_type.bundle.info')->getBundleInfo($entity_type_id);
foreach ($bundles as $bundle_name => $bundle_info) {
$this->assertFieldByName('settings[handler_settings][target_bundles][' . $bundle_name . ']');
}
@@ -106,7 +106,7 @@ class EntityReferenceAdminTest extends WebTestBase {
$this->assertFieldByName('settings[handler_settings][sort][field]', '_none');
$this->assertNoFieldByName('settings[handler_settings][sort][direction]');
// Option 1: sort by field.
$this->drupalPostAjaxForm(NULL, array('settings[handler_settings][sort][field]' => 'nid'), 'settings[handler_settings][sort][field]');
$this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => 'nid'], 'settings[handler_settings][sort][field]');
$this->assertFieldByName('settings[handler_settings][sort][direction]', 'ASC');
// Test that a non-translatable base field is a sort option.
@@ -117,14 +117,14 @@ class EntityReferenceAdminTest extends WebTestBase {
$this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='body.value']");
// Set back to no sort.
$this->drupalPostAjaxForm(NULL, array('settings[handler_settings][sort][field]' => '_none'), 'settings[handler_settings][sort][field]');
$this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => '_none'], 'settings[handler_settings][sort][field]');
$this->assertNoFieldByName('settings[handler_settings][sort][direction]');
// Third step: confirm.
$this->drupalPostForm(NULL, array(
$this->drupalPostForm(NULL, [
'required' => '1',
'settings[handler_settings][target_bundles][' . key($bundles) . ']' => key($bundles),
), t('Save settings'));
], t('Save settings'));
// Check that the field appears in the overview form.
$this->assertFieldByXPath('//table[@id="field-overview"]//tr[@id="field-test"]/td[1]', 'Test label', 'Field was created and appears in the overview page.');
@@ -133,14 +133,14 @@ class EntityReferenceAdminTest extends WebTestBase {
// field is required.
// The first 'Edit' link is for the Body field.
$this->clickLink(t('Edit'), 1);
$this->drupalPostForm(NULL, array(), t('Save settings'));
$this->drupalPostForm(NULL, [], t('Save settings'));
// Switch the target type to 'taxonomy_term' and check that the settings
// specific to its selection handler are displayed.
$field_name = 'node.' . $this->type . '.field_test';
$edit = array(
$edit = [
'settings[target_type]' => 'taxonomy_term',
);
];
$this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
$this->drupalGet($bundle_path . '/fields/' . $field_name);
$this->assertFieldByName('settings[handler_settings][auto_create]');
@@ -148,106 +148,115 @@ class EntityReferenceAdminTest extends WebTestBase {
// Switch the target type to 'user' and check that the settings specific to
// its selection handler are displayed.
$field_name = 'node.' . $this->type . '.field_test';
$edit = array(
$edit = [
'settings[target_type]' => 'user',
);
];
$this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
$this->drupalGet($bundle_path . '/fields/' . $field_name);
$this->assertFieldByName('settings[handler_settings][filter][type]', '_none');
// Switch the target type to 'node'.
$field_name = 'node.' . $this->type . '.field_test';
$edit = array(
$edit = [
'settings[target_type]' => 'node',
);
];
$this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
// Try to select the views handler.
$edit = array(
$edit = [
'settings[handler]' => 'views',
);
];
$this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
$this->assertRaw(t('No eligible views were found. <a href=":create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href=":existing">existing view</a>.', array(
$this->assertRaw(t('No eligible views were found. <a href=":create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href=":existing">existing view</a>.', [
':create' => \Drupal::url('views_ui.add'),
':existing' => \Drupal::url('entity.view.collection'),
)));
]));
$this->drupalPostForm(NULL, $edit, t('Save settings'));
// If no eligible view is available we should see a message.
$this->assertText('The views entity selection mode requires a view.');
// Enable the entity_reference_test module which creates an eligible view.
$this->container->get('module_installer')->install(array('entity_reference_test'));
$this->container->get('module_installer')->install(['entity_reference_test']);
$this->resetAll();
$this->drupalGet($bundle_path . '/fields/' . $field_name);
$this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
$edit = array(
$edit = [
'settings[handler_settings][view][view_and_display]' => 'test_entity_reference:entity_reference_1',
);
];
$this->drupalPostForm(NULL, $edit, t('Save settings'));
$this->assertResponse(200);
// Switch the target type to 'entity_test'.
$edit = array(
$edit = [
'settings[target_type]' => 'entity_test',
);
];
$this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
$this->drupalGet($bundle_path . '/fields/' . $field_name);
$edit = array(
$edit = [
'settings[handler]' => 'views',
);
];
$this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
$edit = array(
$edit = [
'required' => FALSE,
'settings[handler_settings][view][view_and_display]' => 'test_entity_reference_entity_test:entity_reference_1',
);
];
$this->drupalPostForm(NULL, $edit, t('Save settings'));
$this->assertResponse(200);
// Create a new view and display it as a entity reference.
$edit = array(
$edit = [
'id' => 'node_test_view',
'label' => 'Node Test View',
'show[wizard_key]' => 'node',
'show[sort]' => 'none',
'page[create]' => 1,
'page[title]' => 'Test Node View',
'page[path]' => 'test/node/view',
'page[style][style_plugin]' => 'default',
'page[style][row_plugin]' => 'fields',
);
];
$this->drupalPostForm('admin/structure/views/add', $edit, t('Save and edit'));
$this->drupalPostForm(NULL, array(), t('Duplicate as Entity Reference'));
$this->drupalPostForm(NULL, [], t('Duplicate as Entity Reference'));
$this->clickLink(t('Settings'));
$edit = array(
$edit = [
'style_options[search_fields][title]' => 'title',
);
];
$this->drupalPostForm(NULL, $edit, t('Apply'));
$this->drupalPostForm('admin/structure/views/view/node_test_view/edit/entity_reference_1', array(), t('Save'));
// Set sort to NID ascending.
$edit = [
'name[node_field_data.nid]' => 1,
];
$this->drupalPostForm('admin/structure/views/nojs/add-handler/node_test_view/entity_reference_1/sort', $edit, t('Add and configure sort criteria'));
$this->drupalPostForm(NULL, NULL, t('Apply'));
$this->drupalPostForm('admin/structure/views/view/node_test_view/edit/entity_reference_1', [], t('Save'));
$this->clickLink(t('Settings'));
// Create a test entity reference field.
$field_name = 'test_entity_ref_field';
$edit = array(
$edit = [
'new_storage_type' => 'field_ui:entity_reference:node',
'label' => 'Test Entity Reference Field',
'field_name' => $field_name,
);
];
$this->drupalPostForm($bundle_path . '/fields/add-field', $edit, t('Save and continue'));
// Set to unlimited.
$edit = array(
$edit = [
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
);
];
$this->drupalPostForm(NULL, $edit, t('Save field settings'));
// Add the view to the test field.
$edit = array(
$edit = [
'settings[handler]' => 'views',
);
];
$this->drupalPostAjaxForm(NULL, $edit, 'settings[handler]');
$edit = array(
$edit = [
'required' => FALSE,
'settings[handler_settings][view][view_and_display]' => 'node_test_view:entity_reference_1',
);
];
$this->drupalPostForm(NULL, $edit, t('Save settings'));
// Create nodes.
@@ -266,34 +275,34 @@ class EntityReferenceAdminTest extends WebTestBase {
$this->drupalGet('node/add/' . $this->type);
$result = $this->xpath('//input[@name="field_test_entity_ref_field[0][target_id]" and contains(@data-autocomplete-path, "/entity_reference_autocomplete/node/views/")]');
$target_url = $this->getAbsoluteUrl($result[0]['data-autocomplete-path']);
$this->drupalGet($target_url, array('query' => array('q' => 'Foo')));
$this->drupalGet($target_url, ['query' => ['q' => 'Foo']]);
$this->assertRaw($node1->getTitle() . ' (' . $node1->id() . ')');
$this->assertRaw($node2->getTitle() . ' (' . $node2->id() . ')');
// Try to add a new node, fill the entity reference field and submit the
// form.
$this->drupalPostForm('node/add/' . $this->type, [], t('Add another item'));
$edit = array(
$edit = [
'title[0][value]' => 'Example',
'field_test_entity_ref_field[0][target_id]' => 'Foo Node (' . $node1->id() . ')',
'field_test_entity_ref_field[1][target_id]' => 'Foo Node (' . $node2->id() . ')',
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertResponse(200);
$edit = array(
$edit = [
'title[0][value]' => 'Example',
'field_test_entity_ref_field[0][target_id]' => 'Test'
);
];
$this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
// Assert that entity reference autocomplete field is validated.
$this->assertText(t('There are no entities matching "@entity"', ['@entity' => 'Test']));
$edit = array(
$edit = [
'title[0][value]' => 'Test',
'field_test_entity_ref_field[0][target_id]' => $node1->getTitle()
);
];
$this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
// Assert the results multiple times to avoid sorting problem of nodes with
@@ -301,16 +310,17 @@ class EntityReferenceAdminTest extends WebTestBase {
$this->assertText(t('Multiple entities match this reference;'));
$this->assertText(t("@node1", ['@node1' => $node1->getTitle() . ' (' . $node1->id() . ')']));
$this->assertText(t("@node2", ['@node2' => $node2->getTitle() . ' (' . $node2->id() . ')']));
$this->assertText(t('Specify the one you want by appending the id in parentheses, like "@example".', ['@example' => $node2->getTitle() . ' (' . $node2->id() . ')']));
$edit = array(
$edit = [
'title[0][value]' => 'Test',
'field_test_entity_ref_field[0][target_id]' => $node1->getTitle() . ' (' . $node1->id() . ')'
);
];
$this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
$this->assertLink($node1->getTitle());
// Tests adding default values to autocomplete widgets.
Vocabulary::create(array('vid' => 'tags', 'name' => 'tags'))->save();
Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
$taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
$field_path = 'node.' . $this->type . '.field_' . $taxonomy_term_field_name;
$this->drupalGet($bundle_path . '/fields/' . $field_path . '/storage');
@@ -341,7 +351,7 @@ class EntityReferenceAdminTest extends WebTestBase {
*/
public function testAvailableFormatters() {
// Create a new vocabulary.
Vocabulary::create(array('vid' => 'tags', 'name' => 'tags'))->save();
Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
// Create entity reference field with taxonomy term as a target.
$taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
@@ -360,42 +370,38 @@ class EntityReferenceAdminTest extends WebTestBase {
// Check for Taxonomy Term select box values.
// Test if Taxonomy Term Entity Reference Field has the correct formatters.
$this->assertFieldSelectOptions('fields[field_' . $taxonomy_term_field_name . '][type]', array(
$this->assertFieldSelectOptions('fields[field_' . $taxonomy_term_field_name . '][type]', [
'entity_reference_label',
'entity_reference_entity_id',
'entity_reference_rss_category',
'entity_reference_entity_view',
'hidden',
));
]);
// Test if User Reference Field has the correct formatters.
// Author should be available for this field.
// RSS Category should not be available for this field.
$this->assertFieldSelectOptions('fields[field_' . $user_field_name . '][type]', array(
$this->assertFieldSelectOptions('fields[field_' . $user_field_name . '][type]', [
'author',
'entity_reference_entity_id',
'entity_reference_entity_view',
'entity_reference_label',
'hidden',
));
]);
// Test if Node Entity Reference Field has the correct formatters.
// RSS Category should not be available for this field.
$this->assertFieldSelectOptions('fields[field_' . $node_field_name . '][type]', array(
$this->assertFieldSelectOptions('fields[field_' . $node_field_name . '][type]', [
'entity_reference_label',
'entity_reference_entity_id',
'entity_reference_entity_view',
'hidden',
));
]);
// Test if Date Format Reference Field has the correct formatters.
// RSS Category & Entity View should not be available for this field.
// This could be any field without a ViewBuilder.
$this->assertFieldSelectOptions('fields[field_' . $date_format_field_name . '][type]', array(
$this->assertFieldSelectOptions('fields[field_' . $date_format_field_name . '][type]', [
'entity_reference_label',
'entity_reference_entity_id',
'hidden',
));
]);
}
/**
@@ -477,7 +483,7 @@ class EntityReferenceAdminTest extends WebTestBase {
// Generate a random field name, must be only lowercase characters.
$field_name = strtolower($this->randomMachineName());
$storage_edit = $field_edit = array();
$storage_edit = $field_edit = [];
$storage_edit['settings[target_type]'] = $target_type;
foreach ($bundles as $bundle) {
$field_edit['settings[handler_settings][target_bundles][' . $bundle . ']'] = TRUE;
@@ -501,7 +507,7 @@ class EntityReferenceAdminTest extends WebTestBase {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertFieldSelectOptions($name, array $expected_options) {
$xpath = $this->buildXPathQuery('//select[@name=:name]', array(':name' => $name));
$xpath = $this->buildXPathQuery('//select[@name=:name]', [':name' => $name]);
$fields = $this->xpath($xpath);
if ($fields) {
$field = $fields[0];
@@ -527,7 +533,7 @@ class EntityReferenceAdminTest extends WebTestBase {
* An array of option values as strings.
*/
protected function getAllOptionsList(\SimpleXMLElement $element) {
$options = array();
$options = [];
// Add all options items.
foreach ($element->option as $option) {
$options[] = (string) $option['value'];
@@ -14,7 +14,7 @@ use Drupal\field\Entity\FieldStorageConfig;
*/
class EntityReferenceFileUploadTest extends WebTestBase {
public static $modules = array('entity_reference', 'node', 'file');
public static $modules = ['entity_reference', 'node', 'file'];
/**
* The name of a content type that will reference $referencedType.
@@ -46,19 +46,19 @@ class EntityReferenceFileUploadTest extends WebTestBase {
$referenced = $this->drupalCreateContentType();
$this->referencedType = $referenced->id();
$this->nodeId = $this->drupalCreateNode(array('type' => $referenced->id()))->id();
$this->nodeId = $this->drupalCreateNode(['type' => $referenced->id()])->id();
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'test_field',
'entity_type' => 'node',
'translatable' => FALSE,
'entity_types' => array(),
'settings' => array(
'entity_types' => [],
'settings' => [
'target_type' => 'node',
),
],
'type' => 'entity_reference',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
))->save();
])->save();
FieldConfig::create([
'label' => 'Entity reference field',
@@ -66,25 +66,25 @@ class EntityReferenceFileUploadTest extends WebTestBase {
'entity_type' => 'node',
'required' => TRUE,
'bundle' => $referencing->id(),
'settings' => array(
'settings' => [
'handler' => 'default',
'handler_settings' => array(
'handler_settings' => [
// Reference a single vocabulary.
'target_bundles' => array(
'target_bundles' => [
$referenced->id(),
),
),
),
],
],
],
])->save();
// Create a file field.
$file_field_name = 'file_field';
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $file_field_name,
'entity_type' => 'node',
'type' => 'file'
));
]);
$field_storage->save();
FieldConfig::create([
'entity_type' => 'node',
@@ -98,12 +98,12 @@ class EntityReferenceFileUploadTest extends WebTestBase {
->setComponent($file_field_name)
->save();
entity_get_form_display('node', $referencing->id(), 'default')
->setComponent('test_field', array(
->setComponent('test_field', [
'type' => 'entity_reference_autocomplete',
))
->setComponent($file_field_name, array(
])
->setComponent($file_field_name, [
'type' => 'file_generic',
))
])
->save();
}
@@ -111,17 +111,17 @@ class EntityReferenceFileUploadTest extends WebTestBase {
* Tests that the autocomplete input element does not cause ajax fatal.
*/
public function testFileUpload() {
$user1 = $this->drupalCreateUser(array('access content', "create $this->referencingType content"));
$user1 = $this->drupalCreateUser(['access content', "create $this->referencingType content"]);
$this->drupalLogin($user1);
$test_file = current($this->drupalGetTestFiles('text'));
$edit['files[file_field_0]'] = drupal_realpath($test_file->uri);
$this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Upload');
$this->assertResponse(200);
$edit = array(
$edit = [
'title[0][value]' => $this->randomMachineName(),
'test_field[0][target_id]' => $this->nodeId,
);
];
$this->drupalPostForm(NULL, $edit, 'Save');
$this->assertResponse(200);
}
@@ -34,30 +34,30 @@ trait EntityReferenceTestTrait {
*
* @see \Drupal\Core\Entity\Plugin\EntityReferenceSelection\SelectionBase::buildConfigurationForm()
*/
protected function createEntityReferenceField($entity_type, $bundle, $field_name, $field_label, $target_entity_type, $selection_handler = 'default', $selection_handler_settings = array(), $cardinality = 1) {
protected function createEntityReferenceField($entity_type, $bundle, $field_name, $field_label, $target_entity_type, $selection_handler = 'default', $selection_handler_settings = [], $cardinality = 1) {
// Look for or add the specified field to the requested entity bundle.
if (!FieldStorageConfig::loadByName($entity_type, $field_name)) {
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $field_name,
'type' => 'entity_reference',
'entity_type' => $entity_type,
'cardinality' => $cardinality,
'settings' => array(
'settings' => [
'target_type' => $target_entity_type,
),
))->save();
],
])->save();
}
if (!FieldConfig::loadByName($entity_type, $bundle, $field_name)) {
FieldConfig::create(array(
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => $entity_type,
'bundle' => $bundle,
'label' => $field_label,
'settings' => array(
'settings' => [
'handler' => $selection_handler,
'handler_settings' => $selection_handler_settings,
),
))->save();
],
])->save();
}
}
@@ -18,7 +18,7 @@ class FieldDefaultValueCallbackTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('node', 'field_test', 'field_ui');
public static $modules = ['node', 'field_test', 'field_ui'];
/**
* The field name.
@@ -37,10 +37,10 @@ class FieldDefaultValueCallbackTest extends WebTestBase {
// Create Article node types.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(array(
$this->drupalCreateContentType([
'type' => 'article',
'name' => 'Article',
));
]);
}
}
@@ -22,12 +22,12 @@ class FieldImportDeleteUninstallUiTest extends FieldTestBase {
*
* @var array
*/
public static $modules = array('entity_test', 'telephone', 'config', 'filter', 'datetime');
public static $modules = ['entity_test', 'telephone', 'config', 'filter', 'datetime'];
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser(array('synchronize configuration')));
$this->drupalLogin($this->drupalCreateUser(['synchronize configuration']));
}
/**
@@ -35,11 +35,11 @@ class FieldImportDeleteUninstallUiTest extends FieldTestBase {
*/
public function testImportDeleteUninstall() {
// Create a telephone field.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_tel',
'entity_type' => 'entity_test',
'type' => 'telephone',
));
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
@@ -47,11 +47,11 @@ class FieldImportDeleteUninstallUiTest extends FieldTestBase {
])->save();
// Create a text field.
$date_field_storage = FieldStorageConfig::create(array(
$date_field_storage = FieldStorageConfig::create([
'field_name' => 'field_date',
'entity_type' => 'entity_test',
'type' => 'datetime',
));
]);
$date_field_storage->save();
FieldConfig::create([
'field_storage' => $date_field_storage,
@@ -73,7 +73,7 @@ class FieldImportDeleteUninstallUiTest extends FieldTestBase {
// Verify entity has been created properly.
$id = $entity->id();
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$this->assertEqual($entity->field_tel->value, $value);
$this->assertEqual($entity->field_tel[0]->value, $value);
@@ -104,12 +104,12 @@ class FieldImportDeleteUninstallUiTest extends FieldTestBase {
// This will purge all the data, delete the field and uninstall the
// Telephone and Text modules.
$this->drupalPostForm(NULL, array(), t('Import all'));
$this->drupalPostForm(NULL, [], t('Import all'));
$this->assertNoText('Field data will be deleted by this synchronization.');
$this->rebuildContainer();
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('telephone'));
$this->assertFalse(\Drupal::entityManager()->loadEntityByUuid('field_storage_config', $field_storage->uuid()), 'The telephone field has been deleted by the configuration synchronization');
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array();
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: [];
$this->assertFalse(isset($deleted_storages[$field_storage->uuid()]), 'Telephone field has been completed removed from the system.');
$this->assertFalse(isset($deleted_storages[$field_storage->uuid()]), 'Text field has been completed removed from the system.');
}
+12 -6
View File
@@ -8,6 +8,9 @@ use Drupal\simpletest\WebTestBase;
/**
* Parent class for Field API tests.
*
* @deprecated Scheduled for removal in Drupal 9.0.0.
* Use \Drupal\Tests\field\Functional\FieldTestBase instead.
*/
abstract class FieldTestBase extends WebTestBase {
@@ -19,8 +22,8 @@ abstract class FieldTestBase extends WebTestBase {
* @return
* An array of random values, in the format expected for field values.
*/
function _generateTestFieldValues($cardinality) {
$values = array();
public function _generateTestFieldValues($cardinality) {
$values = [];
for ($i = 0; $i < $cardinality; $i++) {
// field_test fields treat 0 as 'empty value'.
$values[$i]['value'] = mt_rand(1, 127);
@@ -45,17 +48,20 @@ abstract class FieldTestBase extends WebTestBase {
* @param $column
* (Optional) The name of the column to check. Defaults to 'value'.
*/
function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_DEFAULT, $column = 'value') {
public function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_DEFAULT, $column = 'value') {
// Re-load the entity to make sure we have the latest changes.
\Drupal::entityManager()->getStorage($entity->getEntityTypeId())->resetCache(array($entity->id()));
$e = entity_load($entity->getEntityTypeId(), $entity->id());
$storage = $this->container->get('entity_type.manager')
->getStorage($entity->getEntityTypeId());
$storage->resetCache([$entity->id()]);
$e = $storage->load($entity->id());
$field = $values = $e->getTranslation($langcode)->$field_name;
// Filter out empty values so that they don't mess with the assertions.
$field->filterEmptyItems();
$values = $field->getValue();
$this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
foreach ($expected_values as $key => $value) {
$this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', array('@value' => $value)));
$this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', ['@value' => $value]));
}
}
+118 -110
View File
@@ -6,6 +6,7 @@ use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormState;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\Entity\EntityTestBaseFieldDisplay;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
@@ -24,7 +25,7 @@ class FormTest extends FieldTestBase {
*
* @var array
*/
public static $modules = array('node', 'field_test', 'options', 'entity_test', 'locale');
public static $modules = ['node', 'field_test', 'options', 'entity_test', 'locale'];
/**
* An array of values defining a field single.
@@ -57,40 +58,40 @@ class FormTest extends FieldTestBase {
protected function setUp() {
parent::setUp();
$web_user = $this->drupalCreateUser(array('view test entity', 'administer entity_test content'));
$web_user = $this->drupalCreateUser(['view test entity', 'administer entity_test content']);
$this->drupalLogin($web_user);
$this->fieldStorageSingle = array(
$this->fieldStorageSingle = [
'field_name' => 'field_single',
'entity_type' => 'entity_test',
'type' => 'test_field',
);
$this->fieldStorageMultiple = array(
];
$this->fieldStorageMultiple = [
'field_name' => 'field_multiple',
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => 4,
);
$this->fieldStorageUnlimited = array(
];
$this->fieldStorageUnlimited = [
'field_name' => 'field_unlimited',
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
);
];
$this->field = array(
$this->field = [
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'label' => $this->randomMachineName() . '_label',
'description' => '[site:name]_description',
'weight' => mt_rand(0, 127),
'settings' => array(
'settings' => [
'test_field_setting' => $this->randomMachineName(),
),
);
],
];
}
function testFieldFormSingle() {
public function testFieldFormSingle() {
$field_storage = $this->fieldStorageSingle;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
@@ -114,23 +115,23 @@ class FormTest extends FieldTestBase {
$this->assertNoText('From hook_field_widget_form_alter(): Default form is true.', 'Not default value form in hook_field_widget_form_alter().');
// Submit with invalid value (field-level validation).
$edit = array(
$edit = [
"{$field_name}[0][value]" => -1
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->field['label'])), 'Field validation fails with invalid input.');
$this->assertRaw(t('%name does not accept the value -1.', ['%name' => $this->field['label']]), 'Field validation fails with invalid input.');
// TODO : check that the correct field is flagged for error.
// Create an entity
$value = mt_rand(1, 127);
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$entity = entity_load('entity_test', $id);
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
$entity = EntityTest::load($id);
$this->assertEqual($entity->{$field_name}->value, $value, 'Field value was saved');
// Display edit form.
@@ -140,36 +141,36 @@ class FormTest extends FieldTestBase {
// Update the entity.
$value = mt_rand(1, 127);
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated');
$this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
$entity = entity_load('entity_test', $id);
$this->assertText(t('entity_test @id has been updated.', ['@id' => $id]), 'Entity was updated');
$this->container->get('entity.manager')->getStorage('entity_test')->resetCache([$id]);
$entity = EntityTest::load($id);
$this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated');
// Empty the field.
$value = '';
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value
);
];
$this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save'));
$this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated');
$this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
$entity = entity_load('entity_test', $id);
$this->assertText(t('entity_test @id has been updated.', ['@id' => $id]), 'Entity was updated');
$this->container->get('entity.manager')->getStorage('entity_test')->resetCache([$id]);
$entity = EntityTest::load($id);
$this->assertTrue($entity->{$field_name}->isEmpty(), 'Field was emptied');
}
/**
* Tests field widget default values on entity forms.
*/
function testFieldFormDefaultValue() {
public function testFieldFormDefaultValue() {
$field_storage = $this->fieldStorageSingle;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
$default = rand(1, 127);
$this->field['default_value'] = array(array('value' => $default));
$this->field['default_value'] = [['value' => $default]];
FieldStorageConfig::create($field_storage)->save();
FieldConfig::create($this->field)->save();
entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
@@ -182,18 +183,18 @@ class FormTest extends FieldTestBase {
$this->assertFieldByXpath("//input[@name='{$field_name}[0][value]' and @value='$default']");
// Try to submit an empty value.
$edit = array(
$edit = [
"{$field_name}[0][value]" => '',
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created.');
$entity = entity_load('entity_test', $id);
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created.');
$entity = EntityTest::load($id);
$this->assertTrue($entity->{$field_name}->isEmpty(), 'Field is now empty.');
}
function testFieldFormSingleRequired() {
public function testFieldFormSingleRequired() {
$field_storage = $this->fieldStorageSingle;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
@@ -205,32 +206,32 @@ class FormTest extends FieldTestBase {
->save();
// Submit with missing required value.
$edit = array();
$edit = [];
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
$this->assertRaw(t('@name field is required.', array('@name' => $this->field['label'])), 'Required field with no value fails validation');
$this->assertRaw(t('@name field is required.', ['@name' => $this->field['label']]), 'Required field with no value fails validation');
// Create an entity
$value = mt_rand(1, 127);
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$entity = entity_load('entity_test', $id);
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
$entity = EntityTest::load($id);
$this->assertEqual($entity->{$field_name}->value, $value, 'Field value was saved');
// Edit with missing required value.
$value = '';
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save'));
$this->assertRaw(t('@name field is required.', array('@name' => $this->field['label'])), 'Required field with no value fails validation');
$this->assertRaw(t('@name field is required.', ['@name' => $this->field['label']]), 'Required field with no value fails validation');
}
function testFieldFormUnlimited() {
public function testFieldFormUnlimited() {
$field_storage = $this->fieldStorageUnlimited;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
@@ -250,20 +251,20 @@ class FormTest extends FieldTestBase {
$this->assertTrue(isset($elements[0]), t('aria-describedby attribute is properly placed on multiple value widgets.'));
// Press 'add more' button -> 2 widgets.
$this->drupalPostForm(NULL, array(), t('Add another item'));
$this->drupalPostForm(NULL, [], t('Add another item'));
$this->assertFieldByName("{$field_name}[0][value]", '', 'Widget 1 is displayed');
$this->assertFieldByName("{$field_name}[1][value]", '', 'New widget is displayed');
$this->assertNoField("{$field_name}[2][value]", 'No extraneous widget is displayed');
// TODO : check that non-field inputs are preserved ('title'), etc.
// Yet another time so that we can play with more values -> 3 widgets.
$this->drupalPostForm(NULL, array(), t('Add another item'));
$this->drupalPostForm(NULL, [], t('Add another item'));
// Prepare values and weights.
$count = 3;
$delta_range = $count - 1;
$values = $weights = $pattern = $expected_values = array();
$edit = array();
$values = $weights = $pattern = $expected_values = [];
$edit = [];
for ($delta = 0; $delta <= $delta_range; $delta++) {
// Assign unique random values and weights.
do {
@@ -298,8 +299,8 @@ class FormTest extends FieldTestBase {
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$entity = entity_load('entity_test', $id);
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
$entity = EntityTest::load($id);
ksort($field_values);
$field_values = array_values($field_values);
$this->assertIdentical($entity->{$field_name}->getValue(), $field_values, 'Field values were saved in the correct order');
@@ -329,18 +330,18 @@ class FormTest extends FieldTestBase {
// Display creation form -> 1 widget.
$this->drupalGet('entity_test/add');
// Check that the Required symbol is present for the multifield label.
$element = $this->xpath('//h4[contains(@class, "label") and contains(@class, "js-form-required") and contains(text(), :value)]', array(':value' => $this->field['label']));
$element = $this->xpath('//h4[contains(@class, "label") and contains(@class, "js-form-required") and contains(text(), :value)]', [':value' => $this->field['label']]);
$this->assertTrue(isset($element[0]), 'Required symbol added field label.');
// Check that the label of the field input is visually hidden and contains
// the field title and an indication of the delta for a11y.
$element = $this->xpath('//label[@for=:for and contains(@class, "js-form-required") and contains(text(), :value)]', array(':for' => 'edit-field-unlimited-0-value', ':value' => $this->field['label'] . ' (value 1)'));
$element = $this->xpath('//label[@for=:for and contains(@class, "visually-hidden") and contains(text(), :value)]', [':for' => 'edit-field-unlimited-0-value', ':value' => $this->field['label'] . ' (value 1)']);
$this->assertTrue(isset($element[0]), 'Required symbol not added for field input.');
}
/**
* Tests widget handling of multiple required radios.
*/
function testFieldFormMultivalueWithRequiredRadio() {
public function testFieldFormMultivalueWithRequiredRadio() {
// Create a multivalue test field.
$field_storage = $this->fieldStorageUnlimited;
$field_name = $field_storage['field_name'];
@@ -352,32 +353,32 @@ class FormTest extends FieldTestBase {
->save();
// Add a required radio field.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'required_radio_test',
'entity_type' => 'entity_test',
'type' => 'list_string',
'settings' => array(
'allowed_values' => array('yes' => 'yes', 'no' => 'no'),
),
))->save();
$field = array(
'settings' => [
'allowed_values' => ['yes' => 'yes', 'no' => 'no'],
],
])->save();
$field = [
'field_name' => 'required_radio_test',
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'required' => TRUE,
);
];
FieldConfig::create($field)->save();
entity_get_form_display($field['entity_type'], $field['bundle'], 'default')
->setComponent($field['field_name'], array(
->setComponent($field['field_name'], [
'type' => 'options_buttons',
))
])
->save();
// Display creation form.
$this->drupalGet('entity_test/add');
// Press the 'Add more' button.
$this->drupalPostForm(NULL, array(), t('Add another item'));
$this->drupalPostForm(NULL, [], t('Add another item'));
// Verify that no error is thrown by the radio element.
$this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed.');
@@ -388,7 +389,7 @@ class FormTest extends FieldTestBase {
$this->assertNoField("{$field_name}[2][value]", 'No extraneous widget is displayed');
}
function testFieldFormJSAddMore() {
public function testFieldFormJSAddMore() {
$field_storage = $this->fieldStorageUnlimited;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
@@ -404,13 +405,13 @@ class FormTest extends FieldTestBase {
// Press 'add more' button a couple times -> 3 widgets.
// drupalPostAjaxForm() will not work iteratively, so we add those through
// non-JS submission.
$this->drupalPostForm(NULL, array(), t('Add another item'));
$this->drupalPostForm(NULL, array(), t('Add another item'));
$this->drupalPostForm(NULL, [], t('Add another item'));
$this->drupalPostForm(NULL, [], t('Add another item'));
// Prepare values and weights.
$count = 3;
$delta_range = $count - 1;
$values = $weights = $pattern = $expected_values = $edit = array();
$values = $weights = $pattern = $expected_values = $edit = [];
for ($delta = 0; $delta <= $delta_range; $delta++) {
// Assign unique random values and weights.
do {
@@ -447,7 +448,7 @@ class FormTest extends FieldTestBase {
/**
* Tests widgets handling multiple values.
*/
function testFieldFormMultipleWidget() {
public function testFieldFormMultipleWidget() {
// Create a field with fixed cardinality, configure the form to use a
// "multiple" widget.
$field_storage = $this->fieldStorageMultiple;
@@ -456,9 +457,9 @@ class FormTest extends FieldTestBase {
FieldStorageConfig::create($field_storage)->save();
FieldConfig::create($this->field)->save();
entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'test_field_widget_multiple',
))
])
->save();
// Display creation form.
@@ -466,33 +467,33 @@ class FormTest extends FieldTestBase {
$this->assertFieldByName($field_name, '', 'Widget is displayed.');
// Create entity with three values.
$edit = array(
$edit = [
$field_name => '1, 2, 3',
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
// Check that the values were saved.
$entity_init = entity_load('entity_test', $id);
$this->assertFieldValues($entity_init, $field_name, array(1, 2, 3));
$entity_init = EntityTest::load($id);
$this->assertFieldValues($entity_init, $field_name, [1, 2, 3]);
// Display the form, check that the values are correctly filled in.
$this->drupalGet('entity_test/manage/' . $id . '/edit');
$this->assertFieldByName($field_name, '1, 2, 3', 'Widget is displayed.');
// Submit the form with more values than the field accepts.
$edit = array($field_name => '1, 2, 3, 4, 5');
$edit = [$field_name => '1, 2, 3, 4, 5'];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw('this field cannot hold more than 4 values', 'Form validation failed.');
// Check that the field values were not submitted.
$this->assertFieldValues($entity_init, $field_name, array(1, 2, 3));
$this->assertFieldValues($entity_init, $field_name, [1, 2, 3]);
}
/**
* Tests fields with no 'edit' access.
*/
function testFieldFormAccess() {
public function testFieldFormAccess() {
$entity_type = 'entity_test_rev';
// Create a "regular" field.
$field_storage = $this->fieldStorageSingle;
@@ -510,18 +511,18 @@ class FormTest extends FieldTestBase {
// Create a field with no edit access. See
// field_test_entity_field_access().
$field_storage_no_access = array(
$field_storage_no_access = [
'field_name' => 'field_no_edit_access',
'entity_type' => $entity_type,
'type' => 'test_field',
);
];
$field_name_no_access = $field_storage_no_access['field_name'];
$field_no_access = array(
$field_no_access = [
'field_name' => $field_name_no_access,
'entity_type' => $entity_type,
'bundle' => $entity_type,
'default_value' => array(0 => array('value' => 99)),
);
'default_value' => [0 => ['value' => 99]],
];
FieldStorageConfig::create($field_storage_no_access)->save();
FieldConfig::create($field_no_access)->save();
entity_get_form_display($field_no_access['entity_type'], $field_no_access['bundle'], 'default')
@@ -532,10 +533,10 @@ class FormTest extends FieldTestBase {
// apart from #access.
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 0, 'revision_id' => 0));
->create(['id' => 0, 'revision_id' => 0]);
$display = entity_get_form_display($entity_type, $entity_type, 'default');
$form = array();
$form = [];
$form_state = new FormState();
$display->buildForm($entity, $form, $form_state);
@@ -546,33 +547,37 @@ class FormTest extends FieldTestBase {
$this->assertNoFieldByName("{$field_name_no_access}[0][value]", '', 'Widget is not displayed if field access is denied.');
// Create entity.
$edit = array(
$edit = [
"{$field_name}[0][value]" => 1,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match("|$entity_type/manage/(\d+)|", $this->url, $match);
$id = $match[1];
// Check that the default value was saved.
$entity = entity_load($entity_type, $id);
$storage = $this->container->get('entity_type.manager')
->getStorage($entity_type);
$entity = $storage->load($id);
$this->assertEqual($entity->$field_name_no_access->value, 99, 'Default value was saved for the field with no edit access.');
$this->assertEqual($entity->$field_name->value, 1, 'Entered value vas saved for the field with edit access.');
// Create a new revision.
$edit = array(
$edit = [
"{$field_name}[0][value]" => 2,
'revision' => TRUE,
);
];
$this->drupalPostForm($entity_type . '/manage/' . $id . '/edit', $edit, t('Save'));
// Check that the new revision has the expected values.
$this->container->get('entity.manager')->getStorage($entity_type)->resetCache(array($id));
$entity = entity_load($entity_type, $id);
$storage->resetCache([$id]);
$entity = $storage->load($id);
$this->assertEqual($entity->$field_name_no_access->value, 99, 'New revision has the expected value for the field with no edit access.');
$this->assertEqual($entity->$field_name->value, 2, 'New revision has the expected value for the field with edit access.');
// Check that the revision is also saved in the revisions table.
// $entity = entity_revision_load($entity_type, $entity->getRevisionId());
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->loadRevision($entity->getRevisionId());
$this->assertEqual($entity->$field_name_no_access->value, 99, 'New revision has the expected value for the field with no edit access.');
$this->assertEqual($entity->$field_name->value, 2, 'New revision has the expected value for the field with edit access.');
}
@@ -580,13 +585,13 @@ class FormTest extends FieldTestBase {
/**
* Tests hiding a field in a form.
*/
function testHiddenField() {
public function testHiddenField() {
$entity_type = 'entity_test_rev';
$field_storage = $this->fieldStorageSingle;
$field_storage['entity_type'] = $entity_type;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
$this->field['default_value'] = array(0 => array('value' => 99));
$this->field['default_value'] = [0 => ['value' => 99]];
$this->field['entity_type'] = $entity_type;
$this->field['bundle'] = $entity_type;
FieldStorageConfig::create($field_storage)->save();
@@ -601,21 +606,24 @@ class FormTest extends FieldTestBase {
// Create an entity and test that the default value is assigned correctly to
// the field that uses the hidden widget.
$this->assertNoField("{$field_name}[0][value]", 'The field does not appear in the form');
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm(NULL, [], t('Save'));
preg_match('|' . $entity_type . '/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test_rev @id has been created.', array('@id' => $id)), 'Entity was created');
$entity = entity_load($entity_type, $id);
$this->assertText(t('entity_test_rev @id has been created.', ['@id' => $id]), 'Entity was created');
$storage = $this->container->get('entity_type.manager')
->getStorage($entity_type);
$entity = $storage->load($id);
$this->assertEqual($entity->{$field_name}->value, 99, 'Default value was saved');
// Update the field to remove the default value, and switch to the default
// widget.
$this->field->setDefaultValue(array());
$this->field->setDefaultValue([]);
$this->field->save();
entity_get_form_display($entity_type, $this->field->getTargetBundle(), 'default')
->setComponent($this->field->getName(), array(
->setComponent($this->field->getName(), [
'type' => 'test_field_widget',
))
])
->save();
// Display edit form.
@@ -624,11 +632,11 @@ class FormTest extends FieldTestBase {
// Update the entity.
$value = mt_rand(1, 127);
$edit = array("{$field_name}[0][value]" => $value);
$edit = ["{$field_name}[0][value]" => $value];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertText(t('entity_test_rev @id has been updated.', array('@id' => $id)), 'Entity was updated');
\Drupal::entityManager()->getStorage($entity_type)->resetCache(array($id));
$entity = entity_load($entity_type, $id);
$this->assertText(t('entity_test_rev @id has been updated.', ['@id' => $id]), 'Entity was updated');
$storage->resetCache([$id]);
$entity = $storage->load($id);
$this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated');
// Set the field back to hidden.
@@ -637,12 +645,12 @@ class FormTest extends FieldTestBase {
->save();
// Create a new revision.
$edit = array('revision' => TRUE);
$edit = ['revision' => TRUE];
$this->drupalPostForm($entity_type . '/manage/' . $id . '/edit', $edit, t('Save'));
// Check that the expected value has been carried over to the new revision.
\Drupal::entityManager()->getStorage($entity_type)->resetCache(array($id));
$entity = entity_load($entity_type, $id);
$storage->resetCache([$id]);
$entity = $storage->load($id);
$this->assertEqual($entity->{$field_name}->value, $value, 'New revision has the expected value for the field with the Hidden widget');
}
+68 -43
View File
@@ -17,42 +17,42 @@ class NestedFormTest extends FieldTestBase {
*
* @var array
*/
public static $modules = array('field_test', 'entity_test');
public static $modules = ['field_test', 'entity_test'];
protected function setUp() {
parent::setUp();
$web_user = $this->drupalCreateUser(array('view test entity', 'administer entity_test content'));
$web_user = $this->drupalCreateUser(['view test entity', 'administer entity_test content']);
$this->drupalLogin($web_user);
$this->fieldStorageSingle = array(
$this->fieldStorageSingle = [
'field_name' => 'field_single',
'entity_type' => 'entity_test',
'type' => 'test_field',
);
$this->fieldStorageUnlimited = array(
];
$this->fieldStorageUnlimited = [
'field_name' => 'field_unlimited',
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
);
];
$this->field = array(
$this->field = [
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'label' => $this->randomMachineName() . '_label',
'description' => '[site:name]_description',
'weight' => mt_rand(0, 127),
'settings' => array(
'settings' => [
'test_field_setting' => $this->randomMachineName(),
),
);
],
];
}
/**
* Tests Field API form integration within a subform.
*/
function testNestedFieldForm() {
public function testNestedFieldForm() {
// Add two fields on the 'entity_test'
FieldStorageConfig::create($this->fieldStorageSingle)->save();
FieldStorageConfig::create($this->fieldStorageUnlimited)->save();
@@ -71,17 +71,16 @@ class NestedFormTest extends FieldTestBase {
// Create two entities.
$entity_type = 'entity_test';
$entity_1 = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 1));
$storage = $this->container->get('entity_type.manager')
->getStorage($entity_type);
$entity_1 = $storage->create(['id' => 1]);
$entity_1->enforceIsNew();
$entity_1->field_single->value = 0;
$entity_1->field_unlimited->value = 1;
$entity_1->save();
$entity_2 = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 2));
$entity_2 = $storage->create(['id' => 2]);
$entity_2->enforceIsNew();
$entity_2->field_single->value = 10;
$entity_2->field_unlimited->value = 11;
@@ -95,75 +94,101 @@ class NestedFormTest extends FieldTestBase {
$this->assertFieldByName('entity_2[field_unlimited][0][value]', 11, 'Entity 2: field_unlimited value 0 appears correctly is the form.');
// Submit the form and check that the entities are updated accordingly.
$edit = array(
$edit = [
'field_single[0][value]' => 1,
'field_unlimited[0][value]' => 2,
'field_unlimited[1][value]' => 3,
'entity_2[field_single][0][value]' => 11,
'entity_2[field_unlimited][0][value]' => 12,
'entity_2[field_unlimited][1][value]' => 13,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$entity_1 = entity_load($entity_type, 1);
$entity_2 = entity_load($entity_type, 2);
$this->assertFieldValues($entity_1, 'field_single', array(1));
$this->assertFieldValues($entity_1, 'field_unlimited', array(2, 3));
$this->assertFieldValues($entity_2, 'field_single', array(11));
$this->assertFieldValues($entity_2, 'field_unlimited', array(12, 13));
$entity_1 = $storage->load(1);
$entity_2 = $storage->load(2);
$this->assertFieldValues($entity_1, 'field_single', [1]);
$this->assertFieldValues($entity_1, 'field_unlimited', [2, 3]);
$this->assertFieldValues($entity_2, 'field_single', [11]);
$this->assertFieldValues($entity_2, 'field_unlimited', [12, 13]);
// Submit invalid values and check that errors are reported on the
// correct widgets.
$edit = array(
$edit = [
'field_unlimited[1][value]' => -1,
);
];
$this->drupalPostForm('test-entity/nested/1/2', $edit, t('Save'));
$this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), 'Entity 1: the field validation error was reported.');
$error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-field-unlimited-1-value'));
$this->assertRaw(t('%label does not accept the value -1', ['%label' => 'Unlimited field']), 'Entity 1: the field validation error was reported.');
$error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', [':id' => 'edit-field-unlimited-1-value']);
$this->assertTrue($error_field, 'Entity 1: the error was flagged on the correct element.');
$edit = array(
$edit = [
'entity_2[field_unlimited][1][value]' => -1,
);
];
$this->drupalPostForm('test-entity/nested/1/2', $edit, t('Save'));
$this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), 'Entity 2: the field validation error was reported.');
$error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-entity-2-field-unlimited-1-value'));
$this->assertRaw(t('%label does not accept the value -1', ['%label' => 'Unlimited field']), 'Entity 2: the field validation error was reported.');
$error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', [':id' => 'edit-entity-2-field-unlimited-1-value']);
$this->assertTrue($error_field, 'Entity 2: the error was flagged on the correct element.');
// Test that reordering works on both entities.
$edit = array(
$edit = [
'field_unlimited[0][_weight]' => 0,
'field_unlimited[1][_weight]' => -1,
'entity_2[field_unlimited][0][_weight]' => 0,
'entity_2[field_unlimited][1][_weight]' => -1,
);
];
$this->drupalPostForm('test-entity/nested/1/2', $edit, t('Save'));
$this->assertFieldValues($entity_1, 'field_unlimited', array(3, 2));
$this->assertFieldValues($entity_2, 'field_unlimited', array(13, 12));
$this->assertFieldValues($entity_1, 'field_unlimited', [3, 2]);
$this->assertFieldValues($entity_2, 'field_unlimited', [13, 12]);
// Test the 'add more' buttons. Only Ajax submission is tested, because
// the two 'add more' buttons present in the form have the same #value,
// which confuses drupalPostForm().
// 'Add more' button in the first entity:
$this->drupalGet('test-entity/nested/1/2');
$this->drupalPostAjaxForm(NULL, array(), 'field_unlimited_add_more');
$this->drupalPostAjaxForm(NULL, [], 'field_unlimited_add_more');
$this->assertFieldByName('field_unlimited[0][value]', 3, 'Entity 1: field_unlimited value 0 appears correctly is the form.');
$this->assertFieldByName('field_unlimited[1][value]', 2, 'Entity 1: field_unlimited value 1 appears correctly is the form.');
$this->assertFieldByName('field_unlimited[2][value]', '', 'Entity 1: field_unlimited value 2 appears correctly is the form.');
$this->assertFieldByName('field_unlimited[3][value]', '', 'Entity 1: an empty widget was added for field_unlimited value 3.');
// 'Add more' button in the first entity (changing field values):
$edit = array(
$edit = [
'entity_2[field_unlimited][0][value]' => 13,
'entity_2[field_unlimited][1][value]' => 14,
'entity_2[field_unlimited][2][value]' => 15,
);
];
$this->drupalPostAjaxForm(NULL, $edit, 'entity_2_field_unlimited_add_more');
$this->assertFieldByName('entity_2[field_unlimited][0][value]', 13, 'Entity 2: field_unlimited value 0 appears correctly is the form.');
$this->assertFieldByName('entity_2[field_unlimited][1][value]', 14, 'Entity 2: field_unlimited value 1 appears correctly is the form.');
$this->assertFieldByName('entity_2[field_unlimited][2][value]', 15, 'Entity 2: field_unlimited value 2 appears correctly is the form.');
$this->assertFieldByName('entity_2[field_unlimited][3][value]', '', 'Entity 2: an empty widget was added for field_unlimited value 3.');
// Save the form and check values are saved correctly.
$this->drupalPostForm(NULL, array(), t('Save'));
$this->assertFieldValues($entity_1, 'field_unlimited', array(3, 2));
$this->assertFieldValues($entity_2, 'field_unlimited', array(13, 14, 15));
$this->drupalPostForm(NULL, [], t('Save'));
$this->assertFieldValues($entity_1, 'field_unlimited', [3, 2]);
$this->assertFieldValues($entity_2, 'field_unlimited', [13, 14, 15]);
}
/**
* Tests entity level validation within subforms.
*/
public function testNestedEntityFormEntityLevelValidation() {
// Create two entities.
$storage = $this->container->get('entity_type.manager')
->getStorage('entity_test_constraints');
$entity_1 = $storage->create();
$entity_1->save();
$entity_2 = $storage->create();
$entity_2->save();
// Display the 'combined form'.
$this->drupalGet("test-entity-constraints/nested/{$entity_1->id()}/{$entity_2->id()}");
$this->assertFieldByName('entity_2[changed]', 0, 'Entity 2: changed value appears correctly in the form.');
// Submit the form and check that the entities are updated accordingly.
$edit = ['entity_2[changed]' => REQUEST_TIME - 86400];
$this->drupalPostForm(NULL, $edit, t('Save'));
$elements = $this->cssSelect('.entity-2.error');
$this->assertEqual(1, count($elements), 'The whole nested entity form has been correctly flagged with an error class.');
}
}
@@ -20,11 +20,11 @@ class NumberFieldTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('node', 'entity_test', 'field_ui');
public static $modules = ['node', 'entity_test', 'field_ui'];
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser(array(
$this->drupalLogin($this->drupalCreateUser([
'view test entity',
'administer entity_test content',
'administer content types',
@@ -32,23 +32,23 @@ class NumberFieldTest extends WebTestBase {
'administer node display',
'bypass node access',
'administer entity_test fields',
)));
]));
}
/**
* Test decimal field.
*/
function testNumberDecimalField() {
public function testNumberDecimalField() {
// Create a field with settings to validate.
$field_name = Unicode::strtolower($this->randomMachineName());
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'decimal',
'settings' => array(
'settings' => [
'precision' => 8, 'scale' => 4,
)
))->save();
]
])->save();
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
@@ -56,17 +56,17 @@ class NumberFieldTest extends WebTestBase {
])->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'number',
'settings' => array(
'settings' => [
'placeholder' => '0.00'
),
))
],
])
->save();
entity_get_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'number_decimal',
))
])
->save();
// Display creation form.
@@ -76,107 +76,107 @@ class NumberFieldTest extends WebTestBase {
// Submit a signed decimal value within the allowed precision and scale.
$value = '-1234.5678';
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
$this->assertRaw($value, 'Value is displayed.');
// Try to create entries with more than one decimal separator; assert fail.
$wrong_entries = array(
$wrong_entries = [
'3.14.159',
'0..45469',
'..4589',
'6.459.52',
'6.3..25',
);
];
foreach ($wrong_entries as $wrong_entry) {
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $wrong_entry,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name must be a number.', array('%name' => $field_name)), 'Correctly failed to save decimal value with more than one decimal point.');
$this->assertRaw(t('%name must be a number.', ['%name' => $field_name]), 'Correctly failed to save decimal value with more than one decimal point.');
}
// Try to create entries with minus sign not in the first position.
$wrong_entries = array(
$wrong_entries = [
'3-3',
'4-',
'1.3-',
'1.2-4',
'-10-10',
);
];
foreach ($wrong_entries as $wrong_entry) {
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $wrong_entry,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name must be a number.', array('%name' => $field_name)), 'Correctly failed to save decimal value with minus sign in the wrong position.');
$this->assertRaw(t('%name must be a number.', ['%name' => $field_name]), 'Correctly failed to save decimal value with minus sign in the wrong position.');
}
}
/**
* Test integer field.
*/
function testNumberIntegerField() {
public function testNumberIntegerField() {
$minimum = rand(-4000, -2000);
$maximum = rand(2000, 4000);
// Create a field with settings to validate.
$field_name = Unicode::strtolower($this->randomMachineName());
$storage = FieldStorageConfig::create(array(
$storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'integer',
));
]);
$storage->save();
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'settings' => array(
'settings' => [
'min' => $minimum, 'max' => $maximum, 'prefix' => 'ThePrefix',
)
]
])->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'number',
'settings' => array(
'settings' => [
'placeholder' => '4'
),
))
],
])
->save();
entity_get_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'number_integer',
'settings' => array(
'settings' => [
'prefix_suffix' => FALSE,
),
))
],
])
->save();
// Check the storage schema.
$expected = array(
'columns' => array(
'value' => array(
$expected = [
'columns' => [
'value' => [
'type' => 'int',
'unsigned' => '',
'size' => 'normal'
),
),
'unique keys' => array(),
'indexes' => array(),
'foreign keys' => array()
);
],
],
'unique keys' => [],
'indexes' => [],
'foreign keys' => []
];
$this->assertEqual($storage->getSchema(), $expected);
// Display creation form.
@@ -186,84 +186,84 @@ class NumberFieldTest extends WebTestBase {
// Submit a valid integer
$value = rand($minimum, $maximum);
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
// Try to set a value below the minimum value
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $minimum - 1,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name must be higher than or equal to %minimum.', array('%name' => $field_name, '%minimum' => $minimum)), 'Correctly failed to save integer value less than minimum allowed value.');
$this->assertRaw(t('%name must be higher than or equal to %minimum.', ['%name' => $field_name, '%minimum' => $minimum]), 'Correctly failed to save integer value less than minimum allowed value.');
// Try to set a decimal value
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => 1.5,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name is not a valid number.', array('%name' => $field_name)), 'Correctly failed to save decimal value to integer field.');
$this->assertRaw(t('%name is not a valid number.', ['%name' => $field_name]), 'Correctly failed to save decimal value to integer field.');
// Try to set a value above the maximum value
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $maximum + 1,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name must be lower than or equal to %maximum.', array('%name' => $field_name, '%maximum' => $maximum)), 'Correctly failed to save integer value greater than maximum allowed value.');
$this->assertRaw(t('%name must be lower than or equal to %maximum.', ['%name' => $field_name, '%maximum' => $maximum]), 'Correctly failed to save integer value greater than maximum allowed value.');
// Try to set a wrong integer value.
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => '20-40',
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name must be a number.', array('%name' => $field_name)), 'Correctly failed to save wrong integer value.');
$this->assertRaw(t('%name must be a number.', ['%name' => $field_name]), 'Correctly failed to save wrong integer value.');
// Test with valid entries.
$valid_entries = array(
$valid_entries = [
'-1234',
'0',
'1234',
);
];
foreach ($valid_entries as $valid_entry) {
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $valid_entry,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
$this->assertRaw($valid_entry, 'Value is displayed.');
$this->assertNoFieldByXpath('//div[@content="' . $valid_entry . '"]', NULL, 'The "content" attribute is not present since the Prefix is not being displayed');
}
// Test for the content attribute when a Prefix is displayed. Presumably this also tests for the attribute when a Suffix is displayed.
entity_get_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'number_integer',
'settings' => array(
'settings' => [
'prefix_suffix' => TRUE,
),
))
],
])
->save();
$integer_value = '123';
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $integer_value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
$this->drupalGet('entity_test/' . $id);
$this->assertFieldByXPath('//div[@content="' . $integer_value . '"]', 'ThePrefix' . $integer_value, 'The "content" attribute has been set to the value of the field, and the prefix is being displayed.');
}
@@ -271,14 +271,14 @@ class NumberFieldTest extends WebTestBase {
/**
* Test float field.
*/
function testNumberFloatField() {
public function testNumberFloatField() {
// Create a field with settings to validate.
$field_name = Unicode::strtolower($this->randomMachineName());
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'float',
))->save();
])->save();
FieldConfig::create([
'field_name' => $field_name,
@@ -287,18 +287,18 @@ class NumberFieldTest extends WebTestBase {
])->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'number',
'settings' => array(
'settings' => [
'placeholder' => '0.00'
),
))
],
])
->save();
entity_get_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'number_decimal',
))
])
->save();
// Display creation form.
@@ -308,13 +308,13 @@ class NumberFieldTest extends WebTestBase {
// Submit a signed decimal value within the allowed precision and scale.
$value = '-1234.5678';
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
// Ensure that the 'number_decimal' formatter displays the number with the
// expected rounding.
@@ -322,113 +322,113 @@ class NumberFieldTest extends WebTestBase {
$this->assertRaw(round($value, 2));
// Try to create entries with more than one decimal separator; assert fail.
$wrong_entries = array(
$wrong_entries = [
'3.14.159',
'0..45469',
'..4589',
'6.459.52',
'6.3..25',
);
];
foreach ($wrong_entries as $wrong_entry) {
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $wrong_entry,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name must be a number.', array('%name' => $field_name)), 'Correctly failed to save float value with more than one decimal point.');
$this->assertRaw(t('%name must be a number.', ['%name' => $field_name]), 'Correctly failed to save float value with more than one decimal point.');
}
// Try to create entries with minus sign not in the first position.
$wrong_entries = array(
$wrong_entries = [
'3-3',
'4-',
'1.3-',
'1.2-4',
'-10-10',
);
];
foreach ($wrong_entries as $wrong_entry) {
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$field_name}[0][value]" => $wrong_entry,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw(t('%name must be a number.', array('%name' => $field_name)), 'Correctly failed to save float value with minus sign in the wrong position.');
$this->assertRaw(t('%name must be a number.', ['%name' => $field_name]), 'Correctly failed to save float value with minus sign in the wrong position.');
}
}
/**
* Test default formatter behavior
*/
function testNumberFormatter() {
public function testNumberFormatter() {
$type = Unicode::strtolower($this->randomMachineName());
$float_field = Unicode::strtolower($this->randomMachineName());
$integer_field = Unicode::strtolower($this->randomMachineName());
$thousand_separators = array('', '.', ',', ' ', chr(8201), "'");
$decimal_separators = array('.', ',');
$thousand_separators = ['', '.', ',', ' ', chr(8201), "'"];
$decimal_separators = ['.', ','];
$prefix = $this->randomMachineName();
$suffix = $this->randomMachineName();
$random_float = rand(0, pow(10, 6));
$random_integer = rand(0, pow(10, 6));
// Create a content type containing float and integer fields.
$this->drupalCreateContentType(array('type' => $type));
$this->drupalCreateContentType(['type' => $type]);
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $float_field,
'entity_type' => 'node',
'type' => 'float',
))->save();
])->save();
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $integer_field,
'entity_type' => 'node',
'type' => 'integer',
))->save();
])->save();
FieldConfig::create([
'field_name' => $float_field,
'entity_type' => 'node',
'bundle' => $type,
'settings' => array(
'settings' => [
'prefix' => $prefix,
'suffix' => $suffix
),
],
])->save();
FieldConfig::create([
'field_name' => $integer_field,
'entity_type' => 'node',
'bundle' => $type,
'settings' => array(
'settings' => [
'prefix' => $prefix,
'suffix' => $suffix
),
],
])->save();
entity_get_form_display('node', $type, 'default')
->setComponent($float_field, array(
->setComponent($float_field, [
'type' => 'number',
'settings' => array(
'settings' => [
'placeholder' => '0.00'
),
))
->setComponent($integer_field, array(
],
])
->setComponent($integer_field, [
'type' => 'number',
'settings' => array(
'settings' => [
'placeholder' => '0.00'
),
))
],
])
->save();
entity_get_display('node', $type, 'default')
->setComponent($float_field, array(
->setComponent($float_field, [
'type' => 'number_decimal',
))
->setComponent($integer_field, array(
])
->setComponent($integer_field, [
'type' => 'number_unformatted',
))
])
->save();
// Create a node to test formatters.
@@ -448,15 +448,15 @@ class NumberFieldTest extends WebTestBase {
$decimal_separator = $decimal_separators[array_rand($decimal_separators)];
$scale = rand(0, 10);
$this->drupalPostAjaxForm(NULL, array(), "${float_field}_settings_edit");
$edit = array(
$this->drupalPostAjaxForm(NULL, [], "${float_field}_settings_edit");
$edit = [
"fields[${float_field}][settings_edit_form][settings][prefix_suffix]" => TRUE,
"fields[${float_field}][settings_edit_form][settings][scale]" => $scale,
"fields[${float_field}][settings_edit_form][settings][decimal_separator]" => $decimal_separator,
"fields[${float_field}][settings_edit_form][settings][thousand_separator]" => $thousand_separator,
);
];
$this->drupalPostAjaxForm(NULL, $edit, "${float_field}_plugin_settings_update");
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm(NULL, [], t('Save'));
// Check number_decimal and number_unformatted formatters behavior.
$this->drupalGet('node/' . $node->id());
@@ -466,21 +466,21 @@ class NumberFieldTest extends WebTestBase {
// Configure the number_decimal formatter.
entity_get_display('node', $type, 'default')
->setComponent($integer_field, array(
->setComponent($integer_field, [
'type' => 'number_integer',
))
])
->save();
$this->drupalGet("admin/structure/types/manage/$type/display");
$thousand_separator = $thousand_separators[array_rand($thousand_separators)];
$this->drupalPostAjaxForm(NULL, array(), "${integer_field}_settings_edit");
$edit = array(
$this->drupalPostAjaxForm(NULL, [], "${integer_field}_settings_edit");
$edit = [
"fields[${integer_field}][settings_edit_form][settings][prefix_suffix]" => FALSE,
"fields[${integer_field}][settings_edit_form][settings][thousand_separator]" => $thousand_separator,
);
];
$this->drupalPostAjaxForm(NULL, $edit, "${integer_field}_plugin_settings_update");
$this->drupalPostForm(NULL, array(), t('Save'));
$this->drupalPostForm(NULL, [], t('Save'));
// Check number_integer formatter behavior.
$this->drupalGet('node/' . $node->id());
@@ -492,14 +492,14 @@ class NumberFieldTest extends WebTestBase {
/**
* Tests setting the minimum value of a float field through the interface.
*/
function testCreateNumberFloatField() {
public function testCreateNumberFloatField() {
// Create a float field.
$field_name = Unicode::strtolower($this->randomMachineName());
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'float',
))->save();
])->save();
$field = FieldConfig::create([
'field_name' => $field_name,
@@ -517,14 +517,14 @@ class NumberFieldTest extends WebTestBase {
/**
* Tests setting the minimum value of a decimal field through the interface.
*/
function testCreateNumberDecimalField() {
public function testCreateNumberDecimalField() {
// Create a decimal field.
$field_name = Unicode::strtolower($this->randomMachineName());
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'decimal',
))->save();
])->save();
$field = FieldConfig::create([
'field_name' => $field_name,
@@ -542,18 +542,18 @@ class NumberFieldTest extends WebTestBase {
/**
* Helper function to set the minimum value of a field.
*/
function assertSetMinimumValue($field, $minimum_value) {
public function assertSetMinimumValue($field, $minimum_value) {
$field_configuration_url = 'entity_test/structure/entity_test/fields/entity_test.entity_test.' . $field->getName();
// Set the minimum value.
$edit = array(
$edit = [
'settings[min]' => $minimum_value,
);
];
$this->drupalPostForm($field_configuration_url, $edit, t('Save settings'));
// Check if an error message is shown.
$this->assertNoRaw(t('%name is not a valid number.', array('%name' => t('Minimum'))), 'Saved ' . gettype($minimum_value) . ' value as minimal value on a ' . $field->getType() . ' field');
$this->assertNoRaw(t('%name is not a valid number.', ['%name' => t('Minimum')]), 'Saved ' . gettype($minimum_value) . ' value as minimal value on a ' . $field->getType() . ' field');
// Check if a success message is shown.
$this->assertRaw(t('Saved %label configuration.', array('%label' => $field->getLabel())));
$this->assertRaw(t('Saved %label configuration.', ['%label' => $field->getLabel()]));
// Check if the minimum value was actually set.
$this->drupalGet($field_configuration_url);
$this->assertFieldById('edit-settings-min', $minimum_value, 'Minimal ' . gettype($minimum_value) . ' value was set on a ' . $field->getType() . ' field.');
@@ -3,6 +3,7 @@
namespace Drupal\field\Tests\String;
use Drupal\Component\Utility\Unicode;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\simpletest\WebTestBase;
use Drupal\field\Entity\FieldStorageConfig;
@@ -19,7 +20,7 @@ class StringFieldTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('entity_test', 'file');
public static $modules = ['entity_test', 'file'];
/**
* A user without any special permissions.
@@ -31,7 +32,7 @@ class StringFieldTest extends WebTestBase {
protected function setUp() {
parent::setUp();
$this->webUser = $this->drupalCreateUser(array('view test entity', 'administer entity_test content'));
$this->webUser = $this->drupalCreateUser(['view test entity', 'administer entity_test content']);
$this->drupalLogin($this->webUser);
}
@@ -40,7 +41,7 @@ class StringFieldTest extends WebTestBase {
/**
* Test widgets.
*/
function testTextfieldWidgets() {
public function testTextfieldWidgets() {
$this->_testTextfieldWidgets('string', 'string_textfield');
$this->_testTextfieldWidgets('string_long', 'string_textarea');
}
@@ -48,14 +49,14 @@ class StringFieldTest extends WebTestBase {
/**
* Helper function for testTextfieldWidgets().
*/
function _testTextfieldWidgets($field_type, $widget_type) {
public function _testTextfieldWidgets($field_type, $widget_type) {
// Create a field.
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => $field_type
));
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
@@ -63,12 +64,12 @@ class StringFieldTest extends WebTestBase {
'label' => $this->randomMachineName() . '_label',
])->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => $widget_type,
'settings' => array(
'settings' => [
'placeholder' => 'A placeholder on ' . $widget_type,
),
))
],
])
->save();
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name)
@@ -78,20 +79,20 @@ class StringFieldTest extends WebTestBase {
$this->drupalGet('entity_test/add');
$this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed');
$this->assertNoFieldByName("{$field_name}[0][format]", '1', 'Format selector is not displayed');
$this->assertRaw(format_string('placeholder="A placeholder on @widget_type"', array('@widget_type' => $widget_type)));
$this->assertRaw(format_string('placeholder="A placeholder on @widget_type"', ['@widget_type' => $widget_type]));
// Submit with some value.
$value = $this->randomMachineName();
$edit = array(
$edit = [
"{$field_name}[0][value]" => $value,
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created');
// Display the entity.
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full');
$content = $display->build($entity);
$this->setRawContent(\Drupal::service('renderer')->renderRoot($content));
@@ -25,7 +25,7 @@ abstract class FieldTestBase extends ViewTestBase {
*
* @var array
*/
public static $modules = array('node', 'field_test_views');
public static $modules = ['node', 'field_test_views'];
/**
* Stores the field definitions used by the test.
@@ -51,25 +51,25 @@ abstract class FieldTestBase extends ViewTestBase {
'name' => 'page',
])->save();
ViewTestData::createTestViews(get_class($this), array('field_test_views'));
ViewTestData::createTestViews(get_class($this), ['field_test_views']);
}
function setUpFieldStorages($amount = 3, $type = 'string') {
public function setUpFieldStorages($amount = 3, $type = 'string') {
// Create three fields.
$field_names = array();
$field_names = [];
for ($i = 0; $i < $amount; $i++) {
$field_names[$i] = 'field_name_' . $i;
$this->fieldStorages[$i] = FieldStorageConfig::create(array(
$this->fieldStorages[$i] = FieldStorageConfig::create([
'field_name' => $field_names[$i],
'entity_type' => 'node',
'type' => $type,
));
]);
$this->fieldStorages[$i]->save();
}
return $field_names;
}
function setUpFields($bundle = 'page') {
public function setUpFields($bundle = 'page') {
foreach ($this->fieldStorages as $key => $field_storage) {
$this->fields[$key] = FieldConfig::create([
'field_storage' => $field_storage,
@@ -19,14 +19,14 @@ class FieldUITest extends FieldTestBase {
*
* @var array
*/
public static $testViews = array('test_view_fieldapi');
public static $testViews = ['test_view_fieldapi'];
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('views_ui');
public static $modules = ['views_ui'];
/**
* A user with the 'administer views' permission.
@@ -41,7 +41,7 @@ class FieldUITest extends FieldTestBase {
protected function setUp() {
parent::setUp();
$this->account = $this->drupalCreateUser(array('administer views'));
$this->account = $this->drupalCreateUser(['administer views']);
$this->drupalLogin($this->account);
$this->setUpFieldStorages(1, 'text');
@@ -56,26 +56,26 @@ class FieldUITest extends FieldTestBase {
$this->drupalGet($url);
// Tests the available formatter options.
$result = $this->xpath('//select[@id=:id]/option', array(':id' => 'edit-options-type'));
$result = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-options-type']);
$options = array_map(function($item) {
return (string) $item->attributes()->value[0];
}, $result);
// @todo Replace this sort by assertArray once it's in.
sort($options, SORT_STRING);
$this->assertEqual($options, array('text_default', 'text_trimmed'), 'The text formatters for a simple text field appear as expected.');
$this->assertEqual($options, ['text_default', 'text_trimmed'], 'The text formatters for a simple text field appear as expected.');
$this->drupalPostForm(NULL, array('options[type]' => 'text_trimmed'), t('Apply'));
$this->drupalPostForm(NULL, ['options[type]' => 'text_trimmed'], t('Apply'));
$this->drupalGet($url);
$this->assertOptionSelected('edit-options-type', 'text_trimmed');
$random_number = rand(100, 400);
$this->drupalPostForm(NULL, array('options[settings][trim_length]' => $random_number), t('Apply'));
$this->drupalPostForm(NULL, ['options[settings][trim_length]' => $random_number], t('Apply'));
$this->drupalGet($url);
$this->assertFieldByName('options[settings][trim_length]', $random_number, 'The formatter setting got saved.');
// Save the view and test whether the settings are saved.
$this->drupalPostForm('admin/structure/views/view/test_view_fieldapi', array(), t('Save'));
$this->drupalPostForm('admin/structure/views/view/test_view_fieldapi', [], t('Save'));
$view = Views::getView('test_view_fieldapi');
$view->initHandlers();
$this->assertEqual($view->field['field_name_0']->options['type'], 'text_trimmed');
@@ -101,7 +101,7 @@ class FieldUITest extends FieldTestBase {
*/
public function testHandlerUIAggregation() {
// Enable aggregation.
$edit = array('group_by' => '1');
$edit = ['group_by' => '1'];
$this->drupalPostForm('admin/structure/views/nojs/display/test_view_fieldapi/default/group_by', $edit, t('Apply'));
$url = "admin/structure/views/nojs/handler/test_view_fieldapi/default/field/field_name_0";
@@ -110,13 +110,13 @@ class FieldUITest extends FieldTestBase {
// Test the click sort column options.
// Tests the available formatter options.
$result = $this->xpath('//select[@id=:id]/option', array(':id' => 'edit-options-click-sort-column'));
$result = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-options-click-sort-column']);
$options = array_map(function($item) {
return (string) $item->attributes()->value[0];
}, $result);
sort($options, SORT_STRING);
$this->assertEqual($options, array('format', 'value'), 'The expected sort field options were found.');
$this->assertEqual($options, ['format', 'value'], 'The expected sort field options were found.');
}
/**
@@ -138,7 +138,7 @@ class FieldUITest extends FieldTestBase {
$field->save();
$url = "admin/structure/views/nojs/add-handler/test_view_fieldapi/default/filter";
$this->drupalPostForm($url, ['name[node__' . $field_name . '.' . $field_name . '_value]' => TRUE], t('Add and configure @handler', array('@handler' => t('filter criteria'))));
$this->drupalPostForm($url, ['name[node__' . $field_name . '.' . $field_name . '_value]' => TRUE], t('Add and configure @handler', ['@handler' => t('filter criteria')]));
$this->assertResponse(200);
// Verify that using a boolean field as a filter also results in using the
// boolean plugin.
@@ -146,6 +146,16 @@ class FieldUITest extends FieldTestBase {
$this->assertEqual(t('True'), (string) $option[0]);
$option = $this->xpath('//label[@for="edit-options-value-0"]');
$this->assertEqual(t('False'), (string) $option[0]);
// Expose the filter and see if the 'Any' option is added and if we can save
// it.
$this->drupalPostForm(NULL, [], 'Expose filter');
$option = $this->xpath('//label[@for="edit-options-value-all"]');
$this->assertEqual(t('- Any -'), (string) $option[0]);
$this->drupalPostForm(NULL, ['options[value]' => 'All', 'options[expose][required]' => FALSE], 'Apply');
$this->drupalPostForm(NULL, [], 'Save');
$this->drupalGet('/admin/structure/views/nojs/handler/test_view_fieldapi/default/filter/field_boolean_value');
$this->assertFieldChecked('edit-options-value-all');
}
}
@@ -22,14 +22,14 @@ class HandlerFieldFieldTest extends FieldTestBase {
/**
* {@inheritdoc}
*/
public static $modules = array('node', 'field_test');
public static $modules = ['node', 'field_test'];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = array('test_view_fieldapi');
public static $testViews = ['test_view_fieldapi'];
/**
* Test nodes.
@@ -48,47 +48,47 @@ class HandlerFieldFieldTest extends FieldTestBase {
$this->setUpFieldStorages(3);
// Setup a field with cardinality > 1.
$this->fieldStorages[3] = FieldStorageConfig::create(array(
$this->fieldStorages[3] = FieldStorageConfig::create([
'field_name' => 'field_name_3',
'entity_type' => 'node',
'type' => 'string',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
));
]);
$this->fieldStorages[3]->save();
// Setup a field that will have no value.
$this->fieldStorages[4] = FieldStorageConfig::create(array(
$this->fieldStorages[4] = FieldStorageConfig::create([
'field_name' => 'field_name_4',
'entity_type' => 'node',
'type' => 'string',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
));
]);
$this->fieldStorages[4]->save();
// Setup a text field.
$this->fieldStorages[5] = FieldStorageConfig::create(array(
$this->fieldStorages[5] = FieldStorageConfig::create([
'field_name' => 'field_name_5',
'entity_type' => 'node',
'type' => 'text',
));
]);
$this->fieldStorages[5]->save();
// Setup a text field with access control.
// @see field_test_entity_field_access()
$this->fieldStorages[6] = FieldStorageConfig::create(array(
$this->fieldStorages[6] = FieldStorageConfig::create([
'field_name' => 'field_no_view_access',
'entity_type' => 'node',
'type' => 'text',
));
]);
$this->fieldStorages[6]->save();
$this->setUpFields();
// Create some nodes.
$this->nodes = array();
$this->nodes = [];
for ($i = 0; $i < 3; $i++) {
$edit = array('type' => 'page');
$edit = ['type' => 'page'];
foreach (array(0, 1, 2, 5) as $key) {
foreach ([0, 1, 2, 5] as $key) {
$field_storage = $this->fieldStorages[$key];
$edit[$field_storage->getName()][0]['value'] = $this->randomMachineName(8);
}
@@ -98,7 +98,7 @@ class HandlerFieldFieldTest extends FieldTestBase {
$edit[$this->fieldStorages[3]->getName()][$j]['value'] = $this->randomMachineName(8);
}
// Set this field to be empty.
$edit[$this->fieldStorages[4]->getName()] = array(array('value' => NULL));
$edit[$this->fieldStorages[4]->getName()] = [['value' => NULL]];
$this->nodes[$i] = $this->drupalCreateNode($edit);
}
@@ -171,9 +171,9 @@ class HandlerFieldFieldTest extends FieldTestBase {
$view = Views::getView('test_view_fieldapi');
$this->prepareView($view);
$view->displayHandlers->get('default')->options['fields'][$this->fieldStorages[5]->getName()]['type'] = 'text_trimmed';
$view->displayHandlers->get('default')->options['fields'][$this->fieldStorages[5]->getName()]['settings'] = array(
$view->displayHandlers->get('default')->options['fields'][$this->fieldStorages[5]->getName()]['settings'] = [
'trim_length' => 3,
);
];
$this->executeView($view);
// Make sure that the formatter works as expected.
@@ -196,7 +196,7 @@ class HandlerFieldFieldTest extends FieldTestBase {
for ($i = 0; $i < 3; $i++) {
$rendered_field = $view->style_plugin->getField($i, $field_name);
$items = array();
$items = [];
$pure_items = $this->nodes[$i]->{$field_name}->getValue();
$pure_items = array_splice($pure_items, 0, 3);
foreach ($pure_items as $j => $item) {
@@ -218,7 +218,7 @@ class HandlerFieldFieldTest extends FieldTestBase {
for ($i = 0; $i < 3; $i++) {
$rendered_field = $view->style_plugin->getField($i, $field_name);
$items = array();
$items = [];
$pure_items = $this->nodes[$i]->{$field_name}->getValue();
$pure_items = array_splice($pure_items, 1, 3);
foreach ($pure_items as $j => $item) {
@@ -238,7 +238,7 @@ class HandlerFieldFieldTest extends FieldTestBase {
for ($i = 0; $i < 3; $i++) {
$rendered_field = $view->style_plugin->getField($i, $field_name);
$items = array();
$items = [];
$pure_items = $this->nodes[$i]->{$field_name}->getValue();
array_splice($pure_items, 0, -3);
$pure_items = array_reverse($pure_items);
@@ -259,7 +259,7 @@ class HandlerFieldFieldTest extends FieldTestBase {
for ($i = 0; $i < 3; $i++) {
$rendered_field = $view->style_plugin->getField($i, $field_name);
$items = array();
$items = [];
$pure_items = $this->nodes[$i]->{$field_name}->getValue();
$items[] = $pure_items[0]['value'];
$items[] = $pure_items[4]['value'];
@@ -277,7 +277,7 @@ class HandlerFieldFieldTest extends FieldTestBase {
for ($i = 0; $i < 3; $i++) {
$rendered_field = $view->style_plugin->getField($i, $field_name);
$items = array();
$items = [];
$pure_items = $this->nodes[$i]->{$field_name}->getValue();
$pure_items = array_splice($pure_items, 0, 3);
foreach ($pure_items as $j => $item) {
@@ -18,22 +18,22 @@ class reEnableModuleFieldTest extends WebTestBase {
*
* @var array
*/
public static $modules = array(
public static $modules = [
'field',
'node',
// We use telephone module instead of test_field because test_field is
// hidden and does not display on the admin/modules page.
'telephone'
);
];
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(array('type' => 'article'));
$this->drupalLogin($this->drupalCreateUser(array(
$this->drupalCreateContentType(['type' => 'article']);
$this->drupalLogin($this->drupalCreateUser([
'create article content',
'edit own article content',
)));
]));
}
/**
@@ -41,14 +41,14 @@ class reEnableModuleFieldTest extends WebTestBase {
*
* @see field_system_info_alter()
*/
function testReEnabledField() {
public function testReEnabledField() {
// Add a telephone field to the article content type.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_telephone',
'entity_type' => 'node',
'type' => 'telephone',
));
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
@@ -57,19 +57,19 @@ class reEnableModuleFieldTest extends WebTestBase {
])->save();
entity_get_form_display('node', 'article', 'default')
->setComponent('field_telephone', array(
->setComponent('field_telephone', [
'type' => 'telephone_default',
'settings' => array(
'settings' => [
'placeholder' => '123-456-7890',
),
))
],
])
->save();
entity_get_display('node', 'article', 'default')
->setComponent('field_telephone', array(
->setComponent('field_telephone', [
'type' => 'telephone_link',
'weight' => 1,
))
])
->save();
// Display the article node form and verify the telephone widget is present.
@@ -78,16 +78,16 @@ class reEnableModuleFieldTest extends WebTestBase {
// Submit an article node with a telephone field so data exist for the
// field.
$edit = array(
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_telephone[0][value]' => "123456789",
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertRaw('<a href="tel:123456789">');
// Test that the module can't be uninstalled from the UI while there is data
// for it's fields.
$admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
$admin_user = $this->drupalCreateUser(['access administration pages', 'administer modules']);
$this->drupalLogin($admin_user);
$this->drupalGet('admin/modules/uninstall');
$this->assertText("The Telephone number field type is used in the following field: node.field_telephone");
@@ -95,11 +95,11 @@ class reEnableModuleFieldTest extends WebTestBase {
// Add another telephone field to a different entity type in order to test
// the message for the case when multiple fields are blocking the
// uninstallation of a module.
$field_storage2 = entity_create('field_storage_config', array(
$field_storage2 = entity_create('field_storage_config', [
'field_name' => 'field_telephone_2',
'entity_type' => 'user',
'type' => 'telephone',
));
]);
$field_storage2->save();
FieldConfig::create([
'field_storage' => $field_storage2,
@@ -7,7 +7,7 @@
*/
use Drupal\Core\Database\Database;
use Drupal\Component\Serialization\Yaml;
use Drupal\Core\Serialization\Yaml;
use Drupal\field\Entity\FieldStorageConfig;
$connection = Database::getConnection();
@@ -7,8 +7,8 @@ package: Testing
dependencies:
- text
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -19,7 +19,7 @@ function field_test_entity_type_alter(array &$entity_types) {
* Helper function to enable entity translations.
*/
function field_test_entity_info_translatable($entity_type_id = NULL, $translatable = NULL) {
$stored_value = &drupal_static(__FUNCTION__, array());
$stored_value = &drupal_static(__FUNCTION__, []);
if (isset($entity_type_id)) {
$entity_manager = \Drupal::entityManager();
$original = $entity_manager->getDefinition($entity_type_id);
@@ -34,7 +34,7 @@ function field_test_field_storage_config_update_forbid(FieldStorageConfigInterfa
* Sample 'default value' callback.
*/
function field_test_default_value(FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
return array(array('value' => 99));
return [['value' => 99]];
}
/**
@@ -7,8 +7,8 @@ package: Testing
dependencies:
- entity_test
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -66,7 +66,7 @@ function field_test_memorize($key = NULL, $value = NULL) {
if (!isset($key)) {
$return = $memorize;
$memorize = array();
$memorize = [];
return $return;
}
if (is_array($memorize)) {
@@ -88,11 +88,11 @@ function field_test_field_storage_config_create(FieldStorageConfigInterface $fie
function field_test_entity_display_build_alter(&$output, $context) {
$display_options = $context['display']->getComponent('test_field');
if (isset($display_options['settings']['alter'])) {
$output['test_field'][] = array('#markup' => 'field_test_entity_display_build_alter');
$output['test_field'][] = ['#markup' => 'field_test_entity_display_build_alter'];
}
if (isset($output['test_field'])) {
$output['test_field'][] = array('#markup' => 'entity language is ' . $context['entity']->language()->getId());
$output['test_field'][] = ['#markup' => 'entity language is ' . $context['entity']->language()->getId()];
}
}
@@ -151,15 +151,18 @@ function field_test_entity_extra_field_info_alter(&$info) {
* Implements hook_entity_bundle_field_info_alter().
*/
function field_test_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
if (($field_name = \Drupal::state()->get('field_test_set_constraint', FALSE)) && $entity_type->id() == 'entity_test' && $bundle == 'entity_test' && !empty($fields[$field_name])) {
if (($field_name = \Drupal::state()->get('field_test_constraint', FALSE)) && $entity_type->id() == 'entity_test' && $bundle == 'entity_test' && !empty($fields[$field_name])) {
// Set a property constraint using
// \Drupal\Core\Field\FieldConfigInterface::setPropertyConstraints().
$fields[$field_name]->setPropertyConstraints('value', [
'Range' => [
'min' => 0,
'max' => 32,
'TestField' => [
'value' => -2,
'message' => t('%name does not accept the value @value.', ['%name' => $field_name, '@value' => -2]),
],
]);
}
if (($field_name = \Drupal::state()->get('field_test_add_constraint', FALSE)) && $entity_type->id() == 'entity_test' && $bundle == 'entity_test' && !empty($fields[$field_name])) {
// Add a property constraint using
// \Drupal\Core\Field\FieldConfigInterface::addPropertyConstraints().
$fields[$field_name]->addPropertyConstraints('value', [
'Range' => [
'min' => 0,
@@ -11,3 +11,17 @@ field_test.entity_nested_form:
type: 'entity:entity_test'
requirements:
_permission: 'administer entity_test content'
field_test.entity_constraints_nested_form:
path: '/test-entity-constraints/nested/{entity_1}/{entity_2}'
defaults:
_title: 'Nested entity form'
_form: '\Drupal\field_test\Form\NestedEntityTestForm'
options:
parameters:
entity_1:
type: 'entity:entity_test_constraints'
entity_2:
type: 'entity:entity_test_constraints'
requirements:
_permission: 'administer entity_test content'
@@ -2,6 +2,7 @@
namespace Drupal\field_test\Form;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
@@ -33,21 +34,31 @@ class NestedEntityTestForm extends FormBase {
$form_state->set('entity_2', $entity_2);
$form_display_2 = EntityFormDisplay::collectRenderDisplay($entity_2, 'default');
$form_state->set('form_display_2', $form_display_2);
$form['entity_2'] = array(
$form['entity_2'] = [
'#type' => 'details',
'#title' => t('Second entity'),
'#tree' => TRUE,
'#parents' => array('entity_2'),
'#parents' => ['entity_2'],
'#weight' => 50,
);
'#attributes' => ['class' => ['entity-2']]
];
$form_display_2->buildForm($entity_2, $form['entity_2'], $form_state);
$form['save'] = array(
if ($entity_2 instanceof EntityChangedInterface) {
// Changed must be sent to the client, for later overwrite error checking.
// @see Drupal\field\Tests\NestedFormTest::testNestedEntityFormEntityLevelValidation()
$form['entity_2']['changed'] = [
'#type' => 'hidden',
'#default_value' => $entity_1->getChangedTime(),
];
}
$form['save'] = [
'#type' => 'submit',
'#value' => t('Save'),
'#weight' => 100,
);
];
return $form;
}
@@ -65,7 +76,16 @@ class NestedEntityTestForm extends FormBase {
$entity_2 = $form_state->get('entity_2');
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display_2 */
$form_display_2 = $form_state->get('form_display_2');
$form_display_2->extractFormValues($entity_2, $form['entity_2'], $form_state);
$extracted = $form_display_2->extractFormValues($entity_2, $form['entity_2'], $form_state);
// Extract the values of fields that are not rendered through widgets, by
// simply copying from top-level form values. This leaves the fields that
// are not being edited within this form untouched.
// @see Drupal\field\Tests\NestedFormTest::testNestedEntityFormEntityLevelValidation()
foreach ($form_state->getValues()['entity_2'] as $name => $values) {
if ($entity_2->hasField($name) && !isset($extracted[$name])) {
$entity_2->set($name, $values);
}
}
$form_display_2->validateFormValues($entity_2, $form['entity_2'], $form_state);
}
@@ -81,7 +101,7 @@ class NestedEntityTestForm extends FormBase {
$entity_2 = $form_state->get('entity_2');
$entity_2->save();
drupal_set_message($this->t('test_entities @id_1 and @id_2 have been updated.', array('@id_1' => $entity_1->id(), '@id_2' => $entity_2->id())));
drupal_set_message($this->t('test_entities @id_1 and @id_2 have been updated.', ['@id_1' => $entity_1->id(), '@id_2' => $entity_2->id()]));
}
}
@@ -34,7 +34,7 @@ class TestFieldApplicableFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
return array('#markup' => 'Nothing to see here');
return ['#markup' => 'Nothing to see here'];
}
}
@@ -26,22 +26,22 @@ class TestFieldDefaultFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_formatter_setting' => 'dummy test string',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_formatter_setting'] = array(
$element['test_formatter_setting'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('test_formatter_setting'),
'#required' => TRUE,
);
];
return $element;
}
@@ -49,8 +49,8 @@ class TestFieldDefaultFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting', '@value' => $this->getSetting('test_formatter_setting')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_formatter_setting', '@value' => $this->getSetting('test_formatter_setting')]);
return $summary;
}
@@ -58,10 +58,10 @@ class TestFieldDefaultFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = array('#markup' => $this->getSetting('test_formatter_setting') . '|' . $item->value);
$elements[$delta] = ['#markup' => $this->getSetting('test_formatter_setting') . '|' . $item->value];
}
return $elements;
@@ -23,25 +23,25 @@ class TestFieldEmptyFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_empty_string' => '**EMPTY FIELD**',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
if ($items->isEmpty()) {
// For fields with no value, just add the configured "empty" value.
$elements[0] = array('#markup' => $this->getSetting('test_empty_string'));
$elements[0] = ['#markup' => $this->getSetting('test_empty_string')];
}
else {
foreach ($items as $delta => $item) {
// This formatter only needs to output raw for testing.
$elements[$delta] = array('#markup' => $item->value);
$elements[$delta] = ['#markup' => $item->value];
}
}
@@ -24,22 +24,22 @@ class TestFieldEmptySettingFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'field_empty_setting' => '',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['field_empty_setting'] = array(
$element['field_empty_setting'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('field_empty_setting'),
'#required' => TRUE,
);
];
return $element;
}
@@ -47,7 +47,7 @@ class TestFieldEmptySettingFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary = [];
$setting = $this->getSetting('field_empty_setting');
if (!empty($setting)) {
$summary[] = t('Default empty setting now has a value.');
@@ -59,11 +59,11 @@ class TestFieldEmptySettingFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
if (!empty($items)) {
foreach ($items as $delta => $item) {
$elements[$delta] = array('#markup' => $this->getSetting('field_empty_setting'));
$elements[$delta] = ['#markup' => $this->getSetting('field_empty_setting')];
}
}
@@ -26,23 +26,23 @@ class TestFieldMultipleFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_formatter_setting_multiple' => 'dummy test string',
'alter' => FALSE,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_formatter_setting_multiple'] = array(
$element['test_formatter_setting_multiple'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('test_formatter_setting_multiple'),
'#required' => TRUE,
);
];
return $element;
}
@@ -50,8 +50,8 @@ class TestFieldMultipleFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting_multiple', '@value' => $this->getSetting('test_formatter_setting_multiple')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_formatter_setting_multiple', '@value' => $this->getSetting('test_formatter_setting_multiple')]);
return $summary;
}
@@ -59,14 +59,14 @@ class TestFieldMultipleFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
if (!empty($items)) {
$array = array();
$array = [];
foreach ($items as $delta => $item) {
$array[] = $delta . ':' . $item->value;
}
$elements[0] = array('#markup' => $this->getSetting('test_formatter_setting_multiple') . '|' . implode('|', $array));
$elements[0] = ['#markup' => $this->getSetting('test_formatter_setting_multiple') . '|' . implode('|', $array)];
}
return $elements;
@@ -23,11 +23,11 @@ class TestFieldNoSettingsFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($items as $delta => $item) {
// This formatter only needs to output raw for testing.
$elements[$delta] = array('#markup' => $item->value);
$elements[$delta] = ['#markup' => $item->value];
}
return $elements;
@@ -25,22 +25,22 @@ class TestFieldPrepareViewFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_formatter_setting_additional' => 'dummy test string',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_formatter_setting_additional'] = array(
$element['test_formatter_setting_additional'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('test_formatter_setting_additional'),
'#required' => TRUE,
);
];
return $element;
}
@@ -48,8 +48,8 @@ class TestFieldPrepareViewFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting_additional', '@value' => $this->getSetting('test_formatter_setting_additional')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_formatter_setting_additional', '@value' => $this->getSetting('test_formatter_setting_additional')]);
return $summary;
}
@@ -71,10 +71,10 @@ class TestFieldPrepareViewFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = array('#markup' => $this->getSetting('test_formatter_setting_additional') . '|' . $item->value . '|' . $item->additional_formatter_value);
$elements[$delta] = ['#markup' => $this->getSetting('test_formatter_setting_additional') . '|' . $item->value . '|' . $item->additional_formatter_value];
}
return $elements;
@@ -24,22 +24,22 @@ class TestItem extends FieldItemBase {
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return array(
return [
'test_field_storage_setting' => 'dummy test string',
'changeable' => 'a changeable field storage setting',
'unchangeable' => 'an unchangeable field storage setting',
'translatable_storage_setting' => 'a translatable field storage setting',
) + parent::defaultStorageSettings();
] + parent::defaultStorageSettings();
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return array(
return [
'test_field_setting' => 'dummy test string',
'translatable_field_setting' => 'a translatable field setting',
) + parent::defaultFieldSettings();
] + parent::defaultFieldSettings();
}
/**
@@ -57,30 +57,30 @@ class TestItem extends FieldItemBase {
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'value' => array(
return [
'columns' => [
'value' => [
'type' => 'int',
'size' => 'medium',
),
),
'indexes' => array(
'value' => array('value'),
),
);
],
],
'indexes' => [
'value' => ['value'],
],
];
}
/**
* {@inheritdoc}
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$form['test_field_storage_setting'] = array(
$form['test_field_storage_setting'] = [
'#type' => 'textfield',
'#title' => t('Field test field storage setting'),
'#default_value' => $this->getSetting('test_field_storage_setting'),
'#required' => FALSE,
'#description' => t('A dummy form element to simulate field storage setting.'),
);
];
return $form;
}
@@ -89,13 +89,13 @@ class TestItem extends FieldItemBase {
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$form['test_field_setting'] = array(
$form['test_field_setting'] = [
'#type' => 'textfield',
'#title' => t('Field test field setting'),
'#default_value' => $this->getSetting('test_field_setting'),
'#required' => FALSE,
'#description' => t('A dummy form element to simulate field setting.'),
);
];
return $form;
}
@@ -105,7 +105,7 @@ class TestItem extends FieldItemBase {
*/
public function delete() {
// Reports that delete() method is executed for testing purposes.
field_test_memorize('field_test_field_delete', array($this->getEntity()));
field_test_memorize('field_test_field_delete', [$this->getEntity()]);
}
/**
@@ -115,14 +115,14 @@ class TestItem extends FieldItemBase {
$constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
$constraints = parent::getConstraints();
$constraints[] = $constraint_manager->create('ComplexData', array(
'value' => array(
'TestField' => array(
$constraints[] = $constraint_manager->create('ComplexData', [
'value' => [
'TestField' => [
'value' => -1,
'message' => t('%name does not accept the value @value.', array('%name' => $this->getFieldDefinition()->getLabel(), '@value' => -1)),
)
),
));
'message' => t('%name does not accept the value @value.', ['%name' => $this->getFieldDefinition()->getLabel(), '@value' => -1]),
]
],
]);
return $constraints;
}
@@ -0,0 +1,62 @@
<?php
namespace Drupal\field_test\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldItemBase;
/**
* Defines the 'test_object_field' entity field item.
*
* @FieldType(
* id = "test_object_field",
* label = @Translation("Test object field"),
* description = @Translation("Test field type that has an object to test serialization"),
* default_widget = "test_object_field_widget",
* default_formatter = "object_field_test_default"
* )
*/
class TestObjectItem extends FieldItemBase {
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('any')
->setLabel(t('Value'))
->setRequired(TRUE);
return $properties;
}
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'description' => 'The object item value.',
'type' => 'blob',
'not null' => TRUE,
'serialize' => TRUE,
],
],
];
}
/**
* {@inheritdoc}
*/
public function setValue($values, $notify = TRUE) {
if (isset($values['value'])) {
// @todo Remove this in https://www.drupal.org/node/2788637.
if (is_string($values['value'])) {
$values['value'] = unserialize($values['value']);
}
}
parent::setValue($values, $notify);
}
}
@@ -27,24 +27,24 @@ class TestFieldWidget extends WidgetBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_widget_setting' => 'dummy test string',
'role' => 'anonymous',
'role2' => 'anonymous',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_widget_setting'] = array(
$element['test_widget_setting'] = [
'#type' => 'textfield',
'#title' => t('Field test field widget setting'),
'#description' => t('A dummy form element to simulate field widget setting.'),
'#default_value' => $this->getSetting('test_widget_setting'),
'#required' => FALSE,
);
];
return $element;
}
@@ -52,8 +52,8 @@ class TestFieldWidget extends WidgetBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_widget_setting', '@value' => $this->getSetting('test_widget_setting')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_widget_setting', '@value' => $this->getSetting('test_widget_setting')]);
return $summary;
}
@@ -61,11 +61,11 @@ class TestFieldWidget extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element += array(
$element += [
'#type' => 'textfield',
'#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : '',
);
return array('value' => $element);
];
return ['value' => $element];
}
/**
@@ -29,22 +29,22 @@ class TestFieldWidgetMultiple extends WidgetBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_widget_setting_multiple' => 'dummy test string',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_widget_setting_multiple'] = array(
$element['test_widget_setting_multiple'] = [
'#type' => 'textfield',
'#title' => t('Field test field widget setting'),
'#description' => t('A dummy form element to simulate field widget setting.'),
'#default_value' => $this->getSetting('test_widget_setting_multiple'),
'#required' => FALSE,
);
];
return $element;
}
@@ -52,8 +52,8 @@ class TestFieldWidgetMultiple extends WidgetBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_widget_setting_multiple', '@value' => $this->getSetting('test_widget_setting_multiple')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_widget_setting_multiple', '@value' => $this->getSetting('test_widget_setting_multiple')]);
return $summary;
}
@@ -61,15 +61,15 @@ class TestFieldWidgetMultiple extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$values = array();
$values = [];
foreach ($items as $item) {
$values[] = $item->value;
}
$element += array(
$element += [
'#type' => 'textfield',
'#default_value' => implode(', ', $values),
'#element_validate' => array(array(get_class($this), 'multipleValidate')),
);
'#element_validate' => [[get_class($this), 'multipleValidate']],
];
return $element;
}
@@ -85,9 +85,9 @@ class TestFieldWidgetMultiple extends WidgetBase {
*/
public static function multipleValidate($element, FormStateInterface $form_state) {
$values = array_map('trim', explode(',', $element['#value']));
$items = array();
$items = [];
foreach ($values as $value) {
$items[] = array('value' => $value);
$items[] = ['value' => $value];
}
$form_state->setValueForElement($element, $items);
}
@@ -19,7 +19,7 @@ class TestFieldConstraint extends NotEqualTo {
* {@inheritdoc}
*/
public function getRequiredOptions() {
return array('value');
return ['value'];
}
/**
@@ -0,0 +1,14 @@
name: 'Boolean field Test'
type: module
description: 'Support module for the field and entity display tests.'
# core: 8.x
package: Testing
# version: VERSION
dependencies:
- field
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1502903957
@@ -0,0 +1,18 @@
<?php
/**
* @file
* Module for testing denying access to boolean fields.
*/
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Implements hook_entity_field_access().
*/
function field_test_boolean_access_denied_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
return AccessResult::forbiddenIf($field_definition->getName() === \Drupal::state()->get('field.test_boolean_field_access_field'));
}
@@ -5,8 +5,8 @@ description: 'Support module for the Field API configuration tests.'
package: Testing
# version: VERSION
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -7,8 +7,8 @@ package: Testing
dependencies:
- views
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -8,8 +8,8 @@ dependencies:
- entity_test
- field_test
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -14,11 +14,11 @@ use Drupal\Core\Form\FormStateInterface;
* Implements hook_field_widget_third_party_settings_form().
*/
function field_third_party_test_field_widget_third_party_settings_form(WidgetInterface $plugin, FieldDefinitionInterface $field_definition, $form_mode, $form, FormStateInterface $form_state) {
$element['field_test_widget_third_party_settings_form'] = array(
$element['field_test_widget_third_party_settings_form'] = [
'#type' => 'textfield',
'#title' => t('3rd party widget settings form'),
'#default_value' => $plugin->getThirdPartySetting('field_third_party_test', 'field_test_widget_third_party_settings_form'),
);
];
return $element;
}
@@ -34,11 +34,11 @@ function field_third_party_test_field_widget_settings_summary_alter(&$summary, $
* Implements hook_field_formatter_third_party_settings_form().
*/
function field_third_party_test_field_formatter_third_party_settings_form(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, $view_mode, $form, FormStateInterface $form_state) {
$element['field_test_field_formatter_third_party_settings_form'] = array(
$element['field_test_field_formatter_third_party_settings_form'] = [
'#type' => 'textfield',
'#title' => t('3rd party formatter settings form'),
'#default_value' => $plugin->getThirdPartySetting('field_third_party_test', 'field_test_field_formatter_third_party_settings_form'),
);
];
return $element;
}
@@ -0,0 +1,229 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\node\Entity\Node;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests creating new entity (e.g. taxonomy-term) from an autocomplete widget.
*
* @group entity_reference
*/
class EntityReferenceAutoCreateTest extends BrowserTestBase {
use EntityReferenceTestTrait;
public static $modules = ['node', 'taxonomy'];
/**
* The name of a content type that will reference $referencedType.
*
* @var string
*/
protected $referencingType;
/**
* The name of a content type that will be referenced by $referencingType.
*
* @var string
*/
protected $referencedType;
protected function setUp() {
parent::setUp();
// Create "referencing" and "referenced" node types.
$referencing = $this->drupalCreateContentType();
$this->referencingType = $referencing->id();
$referenced = $this->drupalCreateContentType();
$this->referencedType = $referenced->id();
FieldStorageConfig::create([
'field_name' => 'test_field',
'entity_type' => 'node',
'translatable' => FALSE,
'entity_types' => [],
'settings' => [
'target_type' => 'node',
],
'type' => 'entity_reference',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
FieldConfig::create([
'label' => 'Entity reference field',
'field_name' => 'test_field',
'entity_type' => 'node',
'bundle' => $referencing->id(),
'settings' => [
'handler' => 'default',
'handler_settings' => [
// Reference a single vocabulary.
'target_bundles' => [
$referenced->id(),
],
// Enable auto-create.
'auto_create' => TRUE,
],
],
])->save();
entity_get_display('node', $referencing->id(), 'default')
->setComponent('test_field')
->save();
entity_get_form_display('node', $referencing->id(), 'default')
->setComponent('test_field', [
'type' => 'entity_reference_autocomplete',
])
->save();
$account = $this->drupalCreateUser(['access content', "create $this->referencingType content"]);
$this->drupalLogin($account);
}
/**
* Tests that the autocomplete input element appears and the creation of a new
* entity.
*/
public function testAutoCreate() {
$this->drupalGet('node/add/' . $this->referencingType);
$this->assertFieldByXPath('//input[@id="edit-test-field-0-target-id" and contains(@class, "form-autocomplete")]', NULL, 'The autocomplete input element appears.');
$new_title = $this->randomMachineName();
// Assert referenced node does not exist.
$base_query = \Drupal::entityQuery('node');
$base_query
->condition('type', $this->referencedType)
->condition('title', $new_title);
$query = clone $base_query;
$result = $query->execute();
$this->assertFalse($result, 'Referenced node does not exist yet.');
$edit = [
'title[0][value]' => $this->randomMachineName(),
'test_field[0][target_id]' => $new_title,
];
$this->drupalPostForm("node/add/$this->referencingType", $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);
$referenced_node = Node::load($referenced_nid);
// Assert the referenced node is associated with referencing node.
$result = \Drupal::entityQuery('node')
->condition('type', $this->referencingType)
->execute();
$referencing_nid = key($result);
$referencing_node = Node::load($referencing_nid);
$this->assertEqual($referenced_nid, $referencing_node->test_field->target_id, 'Newly created node is referenced from the referencing node.');
// Now try to view the node and check that the referenced node is shown.
$this->drupalGet('node/' . $referencing_node->id());
$this->assertText($referencing_node->label(), 'Referencing node label found.');
$this->assertText($referenced_node->label(), 'Referenced node label found.');
}
/**
* Tests if an entity reference field having multiple target bundles is
* storing the auto-created entity in the right destination.
*/
public function testMultipleTargetBundles() {
/** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
$vocabularies = [];
for ($i = 0; $i < 2; $i++) {
$vid = Unicode::strtolower($this->randomMachineName());
$vocabularies[$i] = Vocabulary::create([
'name' => $this->randomMachineName(),
'vid' => $vid,
]);
$vocabularies[$i]->save();
}
// Create a taxonomy term entity reference field that saves the auto-created
// taxonomy terms in the second vocabulary from the two that were configured
// as targets.
$field_name = Unicode::strtolower($this->randomMachineName());
$handler_settings = [
'target_bundles' => [
$vocabularies[0]->id() => $vocabularies[0]->id(),
$vocabularies[1]->id() => $vocabularies[1]->id(),
],
'auto_create' => TRUE,
'auto_create_bundle' => $vocabularies[1]->id(),
];
$this->createEntityReferenceField('node', $this->referencingType, $field_name, $this->randomString(), 'taxonomy_term', 'default', $handler_settings);
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $fd */
entity_get_form_display('node', $this->referencingType, 'default')
->setComponent($field_name, ['type' => 'entity_reference_autocomplete'])
->save();
$term_name = $this->randomString();
$edit = [
$field_name . '[0][target_id]' => $term_name,
'title[0][value]' => $this->randomString(),
];
$this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Save');
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = taxonomy_term_load_multiple_by_name($term_name);
$term = reset($term);
// The new term is expected to be stored in the second vocabulary.
$this->assertEqual($vocabularies[1]->id(), $term->bundle());
/** @var \Drupal\field\Entity\FieldConfig $field_config */
$field_config = FieldConfig::loadByName('node', $this->referencingType, $field_name);
$handler_settings = $field_config->getSetting('handler_settings');
// Change the field setting to store the auto-created terms in the first
// vocabulary and test again.
$handler_settings['auto_create_bundle'] = $vocabularies[0]->id();
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
$term_name = $this->randomString();
$edit = [
$field_name . '[0][target_id]' => $term_name,
'title[0][value]' => $this->randomString(),
];
$this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Save');
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = taxonomy_term_load_multiple_by_name($term_name);
$term = reset($term);
// The second term is expected to be stored in the first vocabulary.
$this->assertEqual($vocabularies[0]->id(), $term->bundle());
// @todo Re-enable this test when WebTestBase::curlHeaderCallback() provides
// a way to catch and assert user-triggered errors.
// Test the case when the field config settings are inconsistent.
//unset($handler_settings['auto_create_bundle']);
//$field_config->setSetting('handler_settings', $handler_settings);
//$field_config->save();
//
//$this->drupalGet('node/add/' . $this->referencingType);
//$error_message = sprintf(
// "Create referenced entities if they don't already exist option is enabled but a specific destination bundle is not set. You should re-visit and fix the settings of the '%s' (%s) field.",
// $field_config->getLabel(),
// $field_config->getName()
//);
//$this->assertErrorLogged($error_message);
}
}
@@ -0,0 +1,158 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Component\Utility\Unicode;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\node\Entity\Node;
use Drupal\Tests\BrowserTestBase;
/**
* Tests entity reference field default values storage in CMI.
*
* @group entity_reference
*/
class EntityReferenceFieldDefaultValueTest extends BrowserTestBase {
use SchemaCheckTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['field_ui', 'node'];
/**
* A user with permission to administer content types, node fields, etc.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
// Create default content type.
$this->drupalCreateContentType(['type' => 'reference_content']);
$this->drupalCreateContentType(['type' => 'referenced_content']);
// Create admin user.
$this->adminUser = $this->drupalCreateUser(['access content', 'administer content types', 'administer node fields', 'administer node form display', 'bypass node access']);
$this->drupalLogin($this->adminUser);
}
/**
* Tests that default values are correctly translated to UUIDs in config.
*/
public function testEntityReferenceDefaultValue() {
// Create a node to be referenced.
$referenced_node = $this->drupalCreateNode(['type' => 'referenced_content']);
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'node',
'type' => 'entity_reference',
'settings' => ['target_type' => 'node'],
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'reference_content',
'settings' => [
'handler' => 'default',
'handler_settings' => [
'target_bundles' => ['referenced_content'],
'sort' => ['field' => '_none'],
],
],
]);
$field->save();
// Set created node as default_value.
$field_edit = [
'default_value_input[' . $field_name . '][0][target_id]' => $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')',
];
$this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings'));
// Check that default value is selected in default value form.
$this->drupalGet('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name);
$this->assertRaw('name="default_value_input[' . $field_name . '][0][target_id]" value="' . $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')', 'The default value is selected in instance settings page');
// Check if the ID has been converted to UUID in config entity.
$config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
$this->assertTrue(isset($config_entity['default_value'][0]['target_uuid']), 'Default value contains target_uuid property');
$this->assertEqual($config_entity['default_value'][0]['target_uuid'], $referenced_node->uuid(), 'Content uuid and config entity uuid are the same');
// Ensure the configuration has the expected dependency on the entity that
// is being used a default value.
$this->assertEqual([$referenced_node->getConfigDependencyName()], $config_entity['dependencies']['content']);
// Clear field definitions cache in order to avoid stale cache values.
\Drupal::entityManager()->clearCachedFieldDefinitions();
// Create a new node to check that UUID has been converted to numeric ID.
$new_node = Node::create(['type' => 'reference_content']);
$this->assertEqual($new_node->get($field_name)->offsetGet(0)->target_id, $referenced_node->id());
// Ensure that the entity reference config schemas are correct.
$field_config = $this->config('field.field.node.reference_content.' . $field_name);
$this->assertConfigSchema(\Drupal::service('config.typed'), $field_config->getName(), $field_config->get());
$field_storage_config = $this->config('field.storage.node.' . $field_name);
$this->assertConfigSchema(\Drupal::service('config.typed'), $field_storage_config->getName(), $field_storage_config->get());
}
/**
* Tests that dependencies due to default values can be removed.
*
* @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::onDependencyRemoval()
*/
public function testEntityReferenceDefaultConfigValue() {
// Create a node to be referenced.
$referenced_node_type = $this->drupalCreateContentType(['type' => 'referenced_config_to_delete']);
$referenced_node_type2 = $this->drupalCreateContentType(['type' => 'referenced_config_to_preserve']);
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'node',
'type' => 'entity_reference',
'settings' => ['target_type' => 'node_type'],
'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED,
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'reference_content',
'settings' => [
'handler' => 'default',
'handler_settings' => [
'sort' => ['field' => '_none'],
],
],
]);
$field->save();
// Set created node as default_value.
$field_edit = [
'default_value_input[' . $field_name . '][0][target_id]' => $referenced_node_type->label() . ' (' . $referenced_node_type->id() . ')',
'default_value_input[' . $field_name . '][1][target_id]' => $referenced_node_type2->label() . ' (' . $referenced_node_type2->id() . ')',
];
$this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings'));
// Check that the field has a dependency on the default value.
$config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
$this->assertTrue(in_array($referenced_node_type->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_delete is a dependency of the field.');
$this->assertTrue(in_array($referenced_node_type2->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_preserve is a dependency of the field.');
// Check that the field does not have a dependency on the default value
// after deleting the node type.
$referenced_node_type->delete();
$config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
$this->assertFalse(in_array($referenced_node_type->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_delete not a dependency of the field.');
$this->assertTrue(in_array($referenced_node_type2->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_preserve is a dependency of the field.');
}
}
@@ -0,0 +1,351 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\field\Entity\FieldConfig;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests the translation of entity reference field display on nodes.
*
* @group entity_reference
*/
class EntityReferenceFieldTranslatedReferenceViewTest extends BrowserTestBase {
/**
* Flag indicating whether the field is translatable.
*
* @var bool
*/
protected $translatable = TRUE;
/**
* The langcode of the source language.
*
* @var string
*/
protected $baseLangcode = 'en';
/**
* Target langcode for translation.
*
* @var string
*/
protected $translateToLangcode = 'hu';
/**
* The test entity type name.
*
* @var string
*/
protected $testEntityTypeName = 'node';
/**
* Entity type which have the entity reference field.
*
* @var \Drupal\node\Entity\NodeType
*/
protected $referrerType;
/**
* Entity type which can be referenced.
*
* @var \Drupal\node\Entity\NodeType
*/
protected $referencedType;
/**
* The referrer entity.
*
* @var \Drupal\node\Entity\Node
*/
protected $referrerEntity;
/**
* The entity to refer.
*
* @var \Drupal\node\Entity\Node
*/
protected $referencedEntityWithoutTranslation;
/**
* The entity to refer.
*
* @var \Drupal\node\Entity\Node
*/
protected $referencedEntityWithTranslation;
/**
* The machine name of the entity reference field.
*
* @var string
*/
protected $referenceFieldName = 'test_reference_field';
/**
* The label of the untranslated referenced entity, used in assertions.
*
* @var string
*/
protected $labelOfNotTranslatedReference;
/**
* The original label of the referenced entity, used in assertions.
*
* @var string
*/
protected $originalLabel;
/**
* The translated label of the referenced entity, used in assertions.
*
* @var string
*/
protected $translatedLabel;
/**
* An user with permission to edit the referrer entity.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'language',
'content_translation',
'node',
];
protected function setUp() {
parent::setUp();
$this->labelOfNotTranslatedReference = $this->randomMachineName();
$this->originalLabel = $this->randomMachineName();
$this->translatedLabel = $this->randomMachineName();
$this->setUpLanguages();
// We setup languages, so we need to ensure that the language manager
// and language path processor is updated.
$this->rebuildContainer();
$this->setUpContentTypes();
$this->enableTranslation();
$this->setUpEntityReferenceField();
$this->createContent();
$this->webUser = $this->drupalCreateUser(['edit any ' . $this->referrerType->id() . ' content']);
}
/**
* Tests if the entity is displayed in an entity reference field.
*/
public function testEntityReferenceDisplay() {
// Create a translated referrer entity.
$this->referrerEntity = $this->createReferrerEntity();
$this->assertEntityReferenceDisplay();
$this->assertEntityReferenceFormDisplay();
// Disable translation for referrer content type.
$this->drupalLogin($this->rootUser);
$this->drupalPostForm('admin/config/regional/content-language', ['settings[node][referrer][translatable]' => FALSE], t('Save configuration'));
$this->drupalLogout();
// Create a referrer entity without translation.
$this->referrerEntity = $this->createReferrerEntity(FALSE);
$this->assertEntityReferenceDisplay();
$this->assertEntityReferenceFormDisplay();
}
/**
* Assert entity reference display.
*/
protected function assertEntityReferenceDisplay() {
$url = $this->referrerEntity->urlInfo();
$translation_url = $this->referrerEntity->urlInfo('canonical', ['language' => ConfigurableLanguage::load($this->translateToLangcode)]);
$this->drupalGet($url);
$this->assertText($this->labelOfNotTranslatedReference, 'The label of not translated reference is displayed.');
$this->assertText($this->originalLabel, 'The default label of translated reference is displayed.');
$this->assertNoText($this->translatedLabel, 'The translated label of translated reference is not displayed.');
$this->drupalGet($translation_url);
$this->assertText($this->labelOfNotTranslatedReference, 'The label of not translated reference is displayed.');
$this->assertNoText($this->originalLabel, 'The default label of translated reference is not displayed.');
$this->assertText($this->translatedLabel, 'The translated label of translated reference is displayed.');
}
/**
* Assert entity reference form display.
*/
protected function assertEntityReferenceFormDisplay() {
$this->drupalLogin($this->webUser);
$url = $this->referrerEntity->urlInfo('edit-form');
$translation_url = $this->referrerEntity->urlInfo('edit-form', ['language' => ConfigurableLanguage::load($this->translateToLangcode)]);
$this->drupalGet($url);
$this->assertSession()->fieldValueEquals('test_reference_field[0][target_id]', $this->originalLabel . ' (1)');
$this->assertSession()->fieldValueEquals('test_reference_field[1][target_id]', $this->labelOfNotTranslatedReference . ' (2)');
$this->drupalGet($translation_url);
$this->assertSession()->fieldValueEquals('test_reference_field[0][target_id]', $this->translatedLabel . ' (1)');
$this->assertSession()->fieldValueEquals('test_reference_field[1][target_id]', $this->labelOfNotTranslatedReference . ' (2)');
$this->drupalLogout();
}
/**
* Adds additional languages.
*/
protected function setUpLanguages() {
ConfigurableLanguage::createFromLangcode($this->translateToLangcode)->save();
}
/**
* Creates a test subject contents, with translation.
*/
protected function createContent() {
$this->referencedEntityWithTranslation = $this->createReferencedEntityWithTranslation();
$this->referencedEntityWithoutTranslation = $this->createNotTranslatedReferencedEntity();
}
/**
* Enables translations where it needed.
*/
protected function enableTranslation() {
// Enable translation for the entity types and ensure the change is picked
// up.
\Drupal::service('content_translation.manager')->setEnabled($this->testEntityTypeName, $this->referrerType->id(), TRUE);
\Drupal::service('content_translation.manager')->setEnabled($this->testEntityTypeName, $this->referencedType->id(), TRUE);
drupal_static_reset();
\Drupal::entityManager()->clearCachedDefinitions();
\Drupal::service('router.builder')->rebuild();
\Drupal::service('entity.definition_update_manager')->applyUpdates();
}
/**
* Adds term reference field for the article content type.
*/
protected function setUpEntityReferenceField() {
FieldStorageConfig::create([
'field_name' => $this->referenceFieldName,
'entity_type' => $this->testEntityTypeName,
'type' => 'entity_reference',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'translatable' => $this->translatable,
'settings' => [
'allowed_values' => [
[
'target_type' => $this->testEntityTypeName,
],
],
],
])->save();
FieldConfig::create([
'field_name' => $this->referenceFieldName,
'bundle' => $this->referrerType->id(),
'entity_type' => $this->testEntityTypeName,
])
->save();
entity_get_form_display($this->testEntityTypeName, $this->referrerType->id(), 'default')
->setComponent($this->referenceFieldName, [
'type' => 'entity_reference_autocomplete',
])
->save();
entity_get_display($this->testEntityTypeName, $this->referrerType->id(), 'default')
->setComponent($this->referenceFieldName, [
'type' => 'entity_reference_label',
])
->save();
}
/**
* Create content types.
*/
protected function setUpContentTypes() {
$this->referrerType = $this->drupalCreateContentType([
'type' => 'referrer',
'name' => 'Referrer',
]);
$this->referencedType = $this->drupalCreateContentType([
'type' => 'referenced_page',
'name' => 'Referenced Page',
]);
}
/**
* Create a referenced entity with a translation.
*/
protected function createReferencedEntityWithTranslation() {
/** @var \Drupal\node\Entity\Node $node */
$node = entity_create($this->testEntityTypeName, [
'title' => $this->originalLabel,
'type' => $this->referencedType->id(),
'description' => [
'value' => $this->randomMachineName(),
'format' => 'basic_html',
],
'langcode' => $this->baseLangcode,
]);
$node->save();
$node->addTranslation($this->translateToLangcode, [
'title' => $this->translatedLabel,
]);
$node->save();
return $node;
}
/**
* Create the referenced entity.
*/
protected function createNotTranslatedReferencedEntity() {
/** @var \Drupal\node\Entity\Node $node */
$node = entity_create($this->testEntityTypeName, [
'title' => $this->labelOfNotTranslatedReference,
'type' => $this->referencedType->id(),
'description' => [
'value' => $this->randomMachineName(),
'format' => 'basic_html',
],
'langcode' => $this->baseLangcode,
]);
$node->save();
return $node;
}
/**
* Create the referrer entity.
*/
protected function createReferrerEntity($translatable = TRUE) {
/** @var \Drupal\node\Entity\Node $node */
$node = entity_create($this->testEntityTypeName, [
'title' => $this->randomMachineName(),
'type' => $this->referrerType->id(),
'description' => [
'value' => $this->randomMachineName(),
'format' => 'basic_html',
],
$this->referenceFieldName => [
['target_id' => $this->referencedEntityWithTranslation->id()],
['target_id' => $this->referencedEntityWithoutTranslation->id()],
],
'langcode' => $this->baseLangcode,
]);
if ($translatable) {
$node->addTranslation($this->translateToLangcode, $node->toArray());
}
$node->save();
return $node;
}
}
@@ -0,0 +1,222 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\config\Tests\AssertConfigEntityImportTrait;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
/**
* Tests various Entity reference UI components.
*
* @group entity_reference
*/
class EntityReferenceIntegrationTest extends BrowserTestBase {
use AssertConfigEntityImportTrait;
use EntityReferenceTestTrait;
/**
* The entity type used in this test.
*
* @var string
*/
protected $entityType = 'entity_test';
/**
* The bundle used in this test.
*
* @var string
*/
protected $bundle = 'entity_test';
/**
* The name of the field used in this test.
*
* @var string
*/
protected $fieldName;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['config_test', 'entity_test', 'field_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create a test user.
$web_user = $this->drupalCreateUser(['administer entity_test content', 'administer entity_test fields', 'view test entity']);
$this->drupalLogin($web_user);
}
/**
* Tests the entity reference field with all its supported field widgets.
*/
public function testSupportedEntityTypesAndWidgets() {
foreach ($this->getTestEntities() as $key => $referenced_entities) {
$this->fieldName = 'field_test_' . $referenced_entities[0]->getEntityTypeId();
// Create an Entity reference field.
$this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, $this->fieldName, $referenced_entities[0]->getEntityTypeId(), 'default', [], 2);
// Test the default 'entity_reference_autocomplete' widget.
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName)->save();
$entity_name = $this->randomMachineName();
$edit = [
'name[0][value]' => $entity_name,
$this->fieldName . '[0][target_id]' => $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')',
// Test an input of the entity label without a ' (entity_id)' suffix.
$this->fieldName . '[1][target_id]' => $referenced_entities[1]->label(),
];
$this->drupalPostForm($this->entityType . '/add', $edit, t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Try to post the form again with no modification and check if the field
// values remain the same.
/** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
$storage = $this->container->get('entity_type.manager')->getStorage($this->entityType);
$entity = current($storage->loadByProperties(['name' => $entity_name]));
$this->drupalGet($this->entityType . '/manage/' . $entity->id() . '/edit');
$this->assertFieldByName($this->fieldName . '[0][target_id]', $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')');
$this->assertFieldByName($this->fieldName . '[1][target_id]', $referenced_entities[1]->label() . ' (' . $referenced_entities[1]->id() . ')');
$this->drupalPostForm(NULL, [], t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Test the 'entity_reference_autocomplete_tags' widget.
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName, [
'type' => 'entity_reference_autocomplete_tags',
])->save();
$entity_name = $this->randomMachineName();
$target_id = $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')';
// Test an input of the entity label without a ' (entity_id)' suffix.
$target_id .= ', ' . $referenced_entities[1]->label();
$edit = [
'name[0][value]' => $entity_name,
$this->fieldName . '[target_id]' => $target_id,
];
$this->drupalPostForm($this->entityType . '/add', $edit, t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Try to post the form again with no modification and check if the field
// values remain the same.
$entity = current($storage->loadByProperties(['name' => $entity_name]));
$this->drupalGet($this->entityType . '/manage/' . $entity->id() . '/edit');
$this->assertFieldByName($this->fieldName . '[target_id]', $target_id . ' (' . $referenced_entities[1]->id() . ')');
$this->drupalPostForm(NULL, [], t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Test all the other widgets supported by the entity reference field.
// Since we don't know the form structure for these widgets, just test
// that editing and saving an already created entity works.
$exclude = ['entity_reference_autocomplete', 'entity_reference_autocomplete_tags'];
$entity = current($storage->loadByProperties(['name' => $entity_name]));
$supported_widgets = \Drupal::service('plugin.manager.field.widget')->getOptions('entity_reference');
$supported_widget_types = array_diff(array_keys($supported_widgets), $exclude);
foreach ($supported_widget_types as $widget_type) {
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName, [
'type' => $widget_type,
])->save();
$this->drupalPostForm($this->entityType . '/manage/' . $entity->id() . '/edit', [], t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
}
// Reset to the default 'entity_reference_autocomplete' widget.
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName)->save();
// Set first entity as the default_value.
$field_edit = [
'default_value_input[' . $this->fieldName . '][0][target_id]' => $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')',
];
if ($key == 'content') {
$field_edit['settings[handler_settings][target_bundles][' . $referenced_entities[0]->getEntityTypeId() . ']'] = TRUE;
}
$this->drupalPostForm($this->entityType . '/structure/' . $this->bundle . '/fields/' . $this->entityType . '.' . $this->bundle . '.' . $this->fieldName, $field_edit, t('Save settings'));
// Ensure the configuration has the expected dependency on the entity that
// is being used a default value.
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $this->fieldName);
$this->assertTrue(in_array($referenced_entities[0]->getConfigDependencyName(), $field->getDependencies()[$key]), SafeMarkup::format('Expected @type dependency @name found', ['@type' => $key, '@name' => $referenced_entities[0]->getConfigDependencyName()]));
// Ensure that the field can be imported without change even after the
// default value deleted.
$referenced_entities[0]->delete();
// Reload the field since deleting the default value can change the field.
\Drupal::entityManager()->getStorage($field->getEntityTypeId())->resetCache([$field->id()]);
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $this->fieldName);
$this->assertConfigEntityImport($field);
// Once the default value has been removed after saving the dependency
// should be removed.
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $this->fieldName);
$field->save();
$dependencies = $field->getDependencies();
$this->assertFalse(isset($dependencies[$key]) && in_array($referenced_entities[0]->getConfigDependencyName(), $dependencies[$key]), SafeMarkup::format('@type dependency @name does not exist.', ['@type' => $key, '@name' => $referenced_entities[0]->getConfigDependencyName()]));
}
}
/**
* Asserts that the reference field values are correct.
*
* @param string $entity_name
* The name of the test entity.
* @param \Drupal\Core\Entity\EntityInterface[] $referenced_entities
* An array of referenced entities.
*/
protected function assertFieldValues($entity_name, $referenced_entities) {
$entity = current($this->container->get('entity_type.manager')->getStorage(
$this->entityType)->loadByProperties(['name' => $entity_name]));
$this->assertTrue($entity, format_string('%entity_type: Entity found in the database.', ['%entity_type' => $this->entityType]));
$this->assertEqual($entity->{$this->fieldName}->target_id, $referenced_entities[0]->id());
$this->assertEqual($entity->{$this->fieldName}->entity->id(), $referenced_entities[0]->id());
$this->assertEqual($entity->{$this->fieldName}->entity->label(), $referenced_entities[0]->label());
$this->assertEqual($entity->{$this->fieldName}[1]->target_id, $referenced_entities[1]->id());
$this->assertEqual($entity->{$this->fieldName}[1]->entity->id(), $referenced_entities[1]->id());
$this->assertEqual($entity->{$this->fieldName}[1]->entity->label(), $referenced_entities[1]->label());
}
/**
* Creates two content and two config test entities.
*
* @return array
* An array of entity objects.
*/
protected function getTestEntities() {
$config_entity_1 = entity_create('config_test', ['id' => $this->randomMachineName(), 'label' => $this->randomMachineName()]);
$config_entity_1->save();
$config_entity_2 = entity_create('config_test', ['id' => $this->randomMachineName(), 'label' => $this->randomMachineName()]);
$config_entity_2->save();
$content_entity_1 = EntityTest::create(['name' => $this->randomMachineName()]);
$content_entity_1->save();
$content_entity_2 = EntityTest::create(['name' => $this->randomMachineName()]);
$content_entity_2->save();
return [
'config' => [
$config_entity_1,
$config_entity_2,
],
'content' => [
$content_entity_1,
$content_entity_2,
],
];
}
}
@@ -0,0 +1,78 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
/**
* Tests possible XSS security issues in entity references.
*
* @group entity_reference
*/
class EntityReferenceXSSTest extends BrowserTestBase {
use EntityReferenceTestTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node'];
/**
* Tests markup is escaped in the entity reference select and label formatter.
*/
public function testEntityReferenceXSS() {
$this->drupalCreateContentType(['type' => 'article']);
// Create a node with markup in the title.
$node_type_one = $this->drupalCreateContentType();
$node = [
'type' => $node_type_one->id(),
'title' => '<em>I am kitten</em>',
];
$referenced_node = $this->drupalCreateNode($node);
$node_type_two = $this->drupalCreateContentType(['name' => '<em>bundle with markup</em>']);
$this->drupalCreateNode([
'type' => $node_type_two->id(),
'title' => 'My bundle has markup',
]);
$this->createEntityReferenceField('node', 'article', 'entity_reference_test', 'Entity Reference test', 'node', 'default', ['target_bundles' => [$node_type_one->id(), $node_type_two->id()]]);
EntityFormDisplay::load('node.article.default')
->setComponent('entity_reference_test', ['type' => 'options_select'])
->save();
EntityViewDisplay::load('node.article.default')
->setComponent('entity_reference_test', ['type' => 'entity_reference_label'])
->save();
// Create a node and reference the node with markup in the title.
$this->drupalLogin($this->rootUser);
$this->drupalGet('node/add/article');
$this->assertEscaped($referenced_node->getTitle());
$this->assertEscaped($node_type_two->label());
$edit = [
'title[0][value]' => $this->randomString(),
'entity_reference_test' => $referenced_node->id()
];
$this->drupalPostForm(NULL, $edit, 'Save and publish');
$this->assertEscaped($referenced_node->getTitle());
// Test the options_buttons type.
EntityFormDisplay::load('node.article.default')
->setComponent('entity_reference_test', ['type' => 'options_buttons'])
->save();
$this->drupalGet('node/add/article');
$this->assertEscaped($referenced_node->getTitle());
// options_buttons does not support optgroups.
$this->assertNoText('bundle with markup');
}
}
@@ -0,0 +1,145 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference\Views;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\views\Views;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests entity reference selection handler.
*
* @group entity_reference
*/
class SelectionTest extends BrowserTestBase {
public static $modules = ['node', 'views', 'entity_reference_test', 'entity_test'];
/**
* Nodes for testing.
*
* @var array
*/
protected $nodes = [];
/**
* The entity reference field to test.
*
* @var \Drupal\Core\Field\FieldDefinitionInterface
*/
protected $field;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create nodes.
$type = $this->drupalCreateContentType()->id();
$node1 = $this->drupalCreateNode(['type' => $type]);
$node2 = $this->drupalCreateNode(['type' => $type]);
$node3 = $this->drupalCreateNode();
foreach ([$node1, $node2, $node3] as $node) {
$this->nodes[$node->getType()][$node->id()] = $node->label();
}
// Create a field.
$field_storage = FieldStorageConfig::create([
'field_name' => 'test_field',
'entity_type' => 'entity_test',
'translatable' => FALSE,
'settings' => [
'target_type' => 'node',
],
'type' => 'entity_reference',
'cardinality' => '1',
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'test_bundle',
'settings' => [
'handler' => 'views',
'handler_settings' => [
'view' => [
'view_name' => 'test_entity_reference',
'display_name' => 'entity_reference_1',
'arguments' => [],
],
],
],
]);
$field->save();
$this->field = $field;
}
/**
* Confirm the expected results are returned.
*
* @param array $result
* Query results keyed by node type and nid.
*/
protected function assertResults(array $result) {
$success = FALSE;
foreach ($result as $node_type => $values) {
foreach ($values as $nid => $label) {
if (!$success = $this->nodes[$node_type][$nid] == trim(strip_tags($label))) {
// There was some error, so break.
break;
}
}
}
$this->assertTrue($success, 'Views selection handler returned expected values.');
}
/**
* Tests the selection handler.
*/
public function testSelectionHandler() {
// Get values from selection handler.
$handler = $this->container->get('plugin.manager.entity_reference_selection')->getSelectionHandler($this->field);
$result = $handler->getReferenceableEntities();
$this->assertResults($result);
}
/**
* Tests the selection handler with a relationship.
*/
public function testSelectionHandlerRelationship() {
// Add a relationship to the view.
$view = Views::getView('test_entity_reference');
$view->setDisplay();
$view->displayHandlers->get('default')->setOption('relationships', [
'test_relationship' => [
'id' => 'uid',
'table' => 'node_field_data',
'field' => 'uid',
],
]);
// Add a filter depending on the relationship to the test view.
$view->displayHandlers->get('default')->setOption('filters', [
'uid' => [
'id' => 'uid',
'table' => 'users_field_data',
'field' => 'uid',
'relationship' => 'test_relationship',
]
]);
// Set view to distinct so only one row per node is returned.
$query_options = $view->display_handler->getOption('query');
$query_options['options']['distinct'] = TRUE;
$view->display_handler->setOption('query', $query_options);
$view->save();
// Get values from the selection handler.
$handler = $this->container->get('plugin.manager.entity_reference_selection')->getSelectionHandler($this->field);
$result = $handler->getReferenceableEntities();
$this->assertResults($result);
}
}
@@ -0,0 +1,92 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests Field access.
*
* @group field
*/
class FieldAccessTest extends FieldTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'field_test'];
/**
* Node entity to use in this test.
*
* @var \Drupal\node\Entity\Node
*/
protected $node;
/**
* Field value to test display on nodes.
*
* @var string
*/
protected $testViewFieldValue;
protected function setUp() {
parent::setUp();
$web_user = $this->drupalCreateUser(['view test_view_field content']);
$this->drupalLogin($web_user);
// Create content type.
$content_type_info = $this->drupalCreateContentType();
$content_type = $content_type_info->id();
$field_storage = [
'field_name' => 'test_view_field',
'entity_type' => 'node',
'type' => 'text',
];
FieldStorageConfig::create($field_storage)->save();
$field = [
'field_name' => $field_storage['field_name'],
'entity_type' => 'node',
'bundle' => $content_type,
];
FieldConfig::create($field)->save();
// Assign display properties for the 'default' and 'teaser' view modes.
foreach (['default', 'teaser'] as $view_mode) {
entity_get_display('node', $content_type, $view_mode)
->setComponent($field_storage['field_name'])
->save();
}
// Create test node.
$this->testViewFieldValue = 'This is some text';
$settings = [];
$settings['type'] = $content_type;
$settings['title'] = 'Field view access test';
$settings['test_view_field'] = [['value' => $this->testViewFieldValue]];
$this->node = $this->drupalCreateNode($settings);
}
/**
* Test that hook_entity_field_access() is called.
*/
public function testFieldAccess() {
// Assert the text is visible.
$this->drupalGet('node/' . $this->node->id());
$this->assertText($this->testViewFieldValue);
// Assert the text is not visible for anonymous users.
// The field_test module implements hook_entity_field_access() which will
// specifically target the 'test_view_field' field.
$this->drupalLogout();
$this->drupalGet('node/' . $this->node->id());
$this->assertNoText($this->testViewFieldValue);
}
}
@@ -0,0 +1,59 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests help display for the Field module.
*
* @group field
*/
class FieldHelpTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array.
*/
public static $modules = ['field', 'help'];
// Tests field help implementation without optional core modules enabled.
protected $profile = 'minimal';
/**
* The admin user that will be created.
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
// Create the admin user.
$this->adminUser = $this->drupalCreateUser(['access administration pages', 'view the administration theme']);
}
/**
* Test the Field module's help page.
*/
public function testFieldHelp() {
// Log in the admin user.
$this->drupalLogin($this->adminUser);
// Visit the Help page and make sure no warnings or notices are thrown.
$this->drupalGet('admin/help/field');
// Enable the Options, Email and Field API Test modules.
\Drupal::service('module_installer')->install(['options', 'field_test']);
$this->resetAll();
\Drupal::service('plugin.manager.field.widget')->clearCachedDefinitions();
\Drupal::service('plugin.manager.field.field_type')->clearCachedDefinitions();
$this->drupalGet('admin/help/field');
$this->assertLink('Options', 0, 'Options module is listed on the Field help page.');
$this->assertText('Field API Test', 'Modules with field types that do not implement hook_help are listed.');
$this->assertNoLink('Field API Test', 'Modules with field types that do not implement hook_help are not linked.');
$this->assertNoLink('Link', 'Modules that have not been installed, are not listed.');
}
}
@@ -0,0 +1,65 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Tests\BrowserTestBase;
/**
* Parent class for Field API tests.
*/
abstract class FieldTestBase extends BrowserTestBase {
/**
* Generate random values for a field_test field.
*
* @param $cardinality
* Number of values to generate.
* @return
* An array of random values, in the format expected for field values.
*/
public function _generateTestFieldValues($cardinality) {
$values = [];
for ($i = 0; $i < $cardinality; $i++) {
// field_test fields treat 0 as 'empty value'.
$values[$i]['value'] = mt_rand(1, 127);
}
return $values;
}
/**
* Assert that a field has the expected values in an entity.
*
* This function only checks a single column in the field values.
*
* @param EntityInterface $entity
* The entity to test.
* @param $field_name
* The name of the field to test
* @param $expected_values
* The array of expected values.
* @param $langcode
* (Optional) The language code for the values. Defaults to
* \Drupal\Core\Language\LanguageInterface::LANGCODE_DEFAULT.
* @param $column
* (Optional) The name of the column to check. Defaults to 'value'.
*/
public function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_DEFAULT, $column = 'value') {
// Re-load the entity to make sure we have the latest changes.
$storage = $this->container->get('entity_type.manager')
->getStorage($entity->getEntityTypeId());
$storage->resetCache([$entity->id()]);
$e = $storage->load($entity->id());
$field = $values = $e->getTranslation($langcode)->$field_name;
// Filter out empty values so that they don't mess with the assertions.
$field->filterEmptyItems();
$values = $field->getValue();
$this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
foreach ($expected_values as $key => $value) {
$this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', ['@value' => $value]));
}
}
}
@@ -0,0 +1,136 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\Component\Utility\Unicode;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\language\Entity\ConfigurableLanguage;
/**
* Tests multilanguage fields logic that require a full environment.
*
* @group field
*/
class TranslationWebTest extends FieldTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['language', 'field_test', 'entity_test'];
/**
* The name of the field to use in this test.
*
* @var string
*/
protected $fieldName;
/**
* The name of the entity type to use in this test.
*
* @var string
*/
protected $entityTypeId = 'entity_test_mulrev';
/**
* The field storage to use in this test.
*
* @var \Drupal\field\Entity\FieldStorageConfig
*/
protected $fieldStorage;
/**
* The field to use in this test.
*
* @var \Drupal\field\Entity\FieldConfig
*/
protected $field;
protected function setUp() {
parent::setUp();
$this->fieldName = Unicode::strtolower($this->randomMachineName() . '_field_name');
$field_storage = [
'field_name' => $this->fieldName,
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 4,
];
FieldStorageConfig::create($field_storage)->save();
$this->fieldStorage = FieldStorageConfig::load($this->entityTypeId . '.' . $this->fieldName);
$field = [
'field_storage' => $this->fieldStorage,
'bundle' => $this->entityTypeId,
];
FieldConfig::create($field)->save();
$this->field = FieldConfig::load($this->entityTypeId . '.' . $field['bundle'] . '.' . $this->fieldName);
entity_get_form_display($this->entityTypeId, $this->entityTypeId, 'default')
->setComponent($this->fieldName)
->save();
for ($i = 0; $i < 3; ++$i) {
ConfigurableLanguage::create([
'id' => 'l' . $i,
'label' => $this->randomString(),
])->save();
}
}
/**
* Tests field translations when creating a new revision.
*/
public function testFieldFormTranslationRevisions() {
$web_user = $this->drupalCreateUser(['view test entity', 'administer entity_test content']);
$this->drupalLogin($web_user);
// Prepare the field translations.
field_test_entity_info_translatable($this->entityTypeId, TRUE);
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create();
$available_langcodes = array_flip(array_keys($this->container->get('language_manager')->getLanguages()));
$field_name = $this->fieldStorage->getName();
// Store the field translations.
ksort($available_langcodes);
$entity->langcode->value = key($available_langcodes);
foreach ($available_langcodes as $langcode => $value) {
$translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
$translation->{$field_name}->value = $value + 1;
}
$entity->save();
// Create a new revision.
$edit = [
"{$field_name}[0][value]" => $entity->{$field_name}->value,
'revision' => TRUE,
];
$this->drupalPostForm($this->entityTypeId . '/manage/' . $entity->id() . '/edit', $edit, t('Save'));
// Check translation revisions.
$this->checkTranslationRevisions($entity->id(), $entity->getRevisionId(), $available_langcodes);
$this->checkTranslationRevisions($entity->id(), $entity->getRevisionId() + 1, $available_langcodes);
}
/**
* Check if the field translation attached to the entity revision identified
* by the passed arguments were correctly stored.
*/
private function checkTranslationRevisions($id, $revision_id, $available_langcodes) {
$field_name = $this->fieldStorage->getName();
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->loadRevision($revision_id);
foreach ($available_langcodes as $langcode => $value) {
$passed = $entity->getTranslation($langcode)->{$field_name}->value == $value + 1;
$this->assertTrue($passed, format_string('The @language translation for revision @revision was correctly stored', ['@language' => $langcode, '@revision' => $entity->getRevisionId()]));
}
}
}
@@ -23,11 +23,11 @@ class BooleanItemTest extends FieldKernelTestBase {
parent::setUp();
// Create a boolean field and storage for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_boolean',
'entity_type' => 'entity_test',
'type' => 'boolean',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_boolean',
@@ -36,9 +36,9 @@ class BooleanItemTest extends FieldKernelTestBase {
// Create a form display for the default form mode.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent('field_boolean', array(
->setComponent('field_boolean', [
'type' => 'boolean_checkbox',
))
])
->save();
}
@@ -55,7 +55,7 @@ class BooleanItemTest extends FieldKernelTestBase {
// Verify entity has been created properly.
$id = $entity->id();
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$this->assertTrue($entity->field_boolean instanceof FieldItemListInterface, 'Field implements interface.');
$this->assertTrue($entity->field_boolean[0] instanceof FieldItemInterface, 'Field item implements interface.');
$this->assertEqual($entity->field_boolean->value, $value);
@@ -68,7 +68,7 @@ class BooleanItemTest extends FieldKernelTestBase {
// Read changed entity and assert changed values.
$entity->save();
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$this->assertEqual($entity->field_boolean->value, $new_value);
// Test sample item generation.
@@ -58,7 +58,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
* @param $actual_hooks
* The array of actual hook invocations recorded by field_test_memorize().
*/
function checkHooksInvocations($expected_hooks, $actual_hooks) {
public function checkHooksInvocations($expected_hooks, $actual_hooks) {
foreach ($expected_hooks as $hook => $invocations) {
$actual_invocations = $actual_hooks[$hook];
@@ -90,31 +90,31 @@ class BulkDeleteTest extends FieldKernelTestBase {
protected function setUp() {
parent::setUp();
$this->fieldStorages = array();
$this->entities = array();
$this->entitiesByBundles = array();
$this->fieldStorages = [];
$this->entities = [];
$this->entitiesByBundles = [];
// Create two bundles.
$this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
$this->bundles = ['bb_1' => 'bb_1', 'bb_2' => 'bb_2'];
foreach ($this->bundles as $name => $desc) {
entity_test_create_bundle($name, $desc);
}
// Create two field storages.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'bf_1',
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 1
));
]);
$field_storage->save();
$this->fieldStorages[] = $field_storage;
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'bf_2',
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 4
));
]);
$field_storage->save();
$this->fieldStorages[] = $field_storage;
@@ -130,14 +130,15 @@ class BulkDeleteTest extends FieldKernelTestBase {
for ($i = 0; $i < 10; $i++) {
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create(array('type' => $bundle));
->create(['type' => $bundle]);
foreach ($this->fieldStorages as $field_storage) {
$entity->{$field_storage->getName()}->setValue($this->_generateTestFieldValues($field_storage->getCardinality()));
}
$entity->save();
}
}
$this->entities = entity_load_multiple($this->entityTypeId);
$this->entities = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)->loadMultiple();
foreach ($this->entities as $entity) {
// This test relies on the entities having stale field definitions
// so that the deleted field can be accessed on them. Access the field
@@ -157,7 +158,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
* This tests how EntityFieldQuery interacts with field deletion and could be
* moved to FieldCrudTestCase, but depends on this class's setUp().
*/
function testDeleteField() {
public function testDeleteField() {
$bundle = reset($this->bundles);
$field_storage = reset($this->fieldStorages);
$field_name = $field_storage->getName();
@@ -174,7 +175,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
$field->delete();
// The field still exists, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 1, 'There is one deleted field');
$field = $fields[$field->uuid()];
$this->assertEqual($field->getTargetBundle(), $bundle, 'The deleted field is for the correct bundle');
@@ -210,11 +211,103 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->assertFalse(array_diff($found, array_keys($this->entities)));
}
/**
* Tests that recreating a field with the name as a deleted field works.
*/
public function testPurgeWithDeletedAndActiveField() {
$bundle = reset($this->bundles);
// Create another field storage.
$field_name = 'bf_3';
$deleted_field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 1
]);
$deleted_field_storage->save();
// Create the field.
FieldConfig::create([
'field_storage' => $deleted_field_storage,
'bundle' => $bundle,
])->save();
for ($i = 0; $i < 20; $i++) {
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create(['type' => $bundle]);
$entity->{$field_name}->setValue($this->_generateTestFieldValues(1));
$entity->save();
}
// Delete the field.
$deleted_field = FieldConfig::loadByName($this->entityTypeId, $bundle, $field_name);
$deleted_field->delete();
$deleted_field_uuid = $deleted_field->uuid();
// Reload the field storage.
$field_storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $deleted_field_storage->uuid(), 'include_deleted' => TRUE]);
$deleted_field_storage = reset($field_storages);
// Create the field again.
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 1
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $bundle,
])->save();
// The field still exists, deleted, with the same field name.
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $deleted_field_uuid, 'include_deleted' => TRUE]);
$this->assertTrue(isset($fields[$deleted_field_uuid]) && $fields[$deleted_field_uuid]->isDeleted(), 'The field exists and is deleted');
$this->assertTrue(isset($fields[$deleted_field_uuid]) && $fields[$deleted_field_uuid]->getName() == $field_name);
for ($i = 0; $i < 10; $i++) {
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create(['type' => $bundle]);
$entity->{$field_name}->setValue($this->_generateTestFieldValues(1));
$entity->save();
}
// Check that the two field storages have different tables.
$storage = \Drupal::entityManager()->getStorage($this->entityTypeId);
/** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
$table_mapping = $storage->getTableMapping();
$deleted_table_name = $table_mapping->getDedicatedDataTableName($deleted_field_storage, TRUE);
$active_table_name = $table_mapping->getDedicatedDataTableName($field_storage);
field_purge_batch(50);
// Ensure the new field still has its table and the deleted one has been
// removed.
$this->assertTrue(\Drupal::database()->schema()->tableExists($active_table_name));
$this->assertFalse(\Drupal::database()->schema()->tableExists($deleted_table_name));
// The field has been removed from the system.
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $deleted_field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is gone');
// Verify there are still 10 entries in the main table.
$count = \Drupal::database()
->select('entity_test__' . $field_name, 'f')
->fields('f', ['entity_id'])
->condition('bundle', $bundle)
->countQuery()
->execute()
->fetchField();
$this->assertEqual($count, 10);
}
/**
* Verify that field data items and fields are purged when a field storage is
* deleted.
*/
function testPurgeField() {
public function testPurgeField() {
// Start recording hook invocations.
field_test_memorize();
@@ -247,7 +340,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
// FieldItemInterface::delete() should have been called once for each entity in the
// bundle.
$actual_hooks = field_test_memorize();
$hooks = array();
$hooks = [];
$entities = $this->entitiesByBundles[$bundle];
foreach ($entities as $id => $entity) {
$hooks['field_test_field_delete'][] = $entity;
@@ -255,19 +348,19 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->checkHooksInvocations($hooks, $actual_hooks);
// The field still exists, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 1, 'There is one deleted field');
// Purge the field.
field_purge_batch($batch_size);
// The field is gone.
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is gone');
// The field storage still exists, not deleted, because it has a second
// field.
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($storages[$field_storage->uuid()]), 'The field storage exists and is not deleted');
}
@@ -275,7 +368,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
* Verify that field storages are preserved and purged correctly as multiple
* fields are deleted and purged.
*/
function testPurgeFieldStorage() {
public function testPurgeFieldStorage() {
// Start recording hook invocations.
field_test_memorize();
@@ -298,7 +391,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
// FieldItemInterface::delete() should have been called once for each entity in the
// bundle.
$actual_hooks = field_test_memorize();
$hooks = array();
$hooks = [];
$entities = $this->entitiesByBundles[$bundle];
foreach ($entities as $id => $entity) {
$hooks['field_test_field_delete'][] = $entity;
@@ -306,17 +399,17 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->checkHooksInvocations($hooks, $actual_hooks);
// The field still exists, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($fields[$field->uuid()]) && $fields[$field->uuid()]->isDeleted(), 'The field exists and is deleted');
// Purge again to purge the field.
field_purge_batch(0);
// The field is gone.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is purged.');
// The field storage still exists, not deleted.
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($storages[$field_storage->uuid()]) && !$storages[$field_storage->uuid()]->isDeleted(), 'The field storage exists and is not deleted');
// Delete the second field.
@@ -333,7 +426,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
// Check hooks invocations (same as above, for the 2nd bundle).
$actual_hooks = field_test_memorize();
$hooks = array();
$hooks = [];
$entities = $this->entitiesByBundles[$bundle];
foreach ($entities as $id => $entity) {
$hooks['field_test_field_delete'][] = $entity;
@@ -341,18 +434,18 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->checkHooksInvocations($hooks, $actual_hooks);
// The field and the storage still exist, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($fields[$field->uuid()]) && $fields[$field->uuid()]->isDeleted(), 'The field exists and is deleted');
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($storages[$field_storage->uuid()]) && $storages[$field_storage->uuid()]->isDeleted(), 'The field storage exists and is deleted');
// Purge again to purge the field and the storage.
field_purge_batch(0);
// The field and the storage are gone.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is purged.');
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertEqual(count($storages), 0, 'The field storage is purged.');
}
@@ -69,33 +69,33 @@ class DisplayApiTest extends FieldKernelTestBase {
$this->label = $this->randomMachineName();
$this->cardinality = 4;
$field_storage = array(
$field_storage = [
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => $this->cardinality,
);
$field = array(
];
$field = [
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'label' => $this->label,
);
];
$this->displayOptions = array(
'default' => array(
$this->displayOptions = [
'default' => [
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $this->randomMachineName(),
),
),
'teaser' => array(
],
],
'teaser' => [
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $this->randomMachineName(),
),
),
);
],
],
];
FieldStorageConfig::create($field_storage)->save();
FieldConfig::create($field)->save();
@@ -104,7 +104,7 @@ class DisplayApiTest extends FieldKernelTestBase {
->setComponent($this->fieldName, $this->displayOptions['default'])
->save();
// Create a display for the teaser view mode.
EntityViewMode::create(array('id' => 'entity_test.teaser', 'targetEntityType' => 'entity_test'))->save();
EntityViewMode::create(['id' => 'entity_test.teaser', 'targetEntityType' => 'entity_test'])->save();
entity_get_display($field['entity_type'], $field['bundle'], 'teaser')
->setComponent($this->fieldName, $this->displayOptions['teaser'])
->save();
@@ -119,11 +119,11 @@ class DisplayApiTest extends FieldKernelTestBase {
/**
* Tests the FieldItemListInterface::view() method.
*/
function testFieldItemListView() {
public function testFieldItemListView() {
$items = $this->entity->get($this->fieldName);
\Drupal::service('theme_handler')->install(['classy']);
\Drupal::service('theme_handler')->setDefault('classy');
$this->config('system.theme')->set('default', 'classy')->save();
// No display settings: check that default display settings are used.
$build = $items->view();
@@ -132,66 +132,66 @@ class DisplayApiTest extends FieldKernelTestBase {
$setting = $settings['test_formatter_setting'];
$this->assertText($this->label, 'Label was displayed.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Display settings: Check hidden field.
$display = array(
$display = [
'label' => 'hidden',
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $this->randomMachineName(),
'alter' => TRUE,
),
);
],
];
$build = $items->view($display);
$this->render($build);
$setting = $display['settings']['test_formatter_setting_multiple'];
$this->assertNoText($this->label, 'Label was not displayed.');
$this->assertText('field_test_entity_display_build_alter', 'Alter fired, display passed.');
$this->assertText('entity language is en', 'Language is placed onto the context.');
$array = array();
$array = [];
foreach ($this->values as $delta => $value) {
$array[] = $delta . ':' . $value['value'];
}
$this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');
// Display settings: Check visually_hidden field.
$display = array(
$display = [
'label' => 'visually_hidden',
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $this->randomMachineName(),
'alter' => TRUE,
),
);
],
];
$build = $items->view($display);
$this->render($build);
$setting = $display['settings']['test_formatter_setting_multiple'];
$this->assertRaw('visually-hidden', 'Label was visually hidden.');
$this->assertText('field_test_entity_display_build_alter', 'Alter fired, display passed.');
$this->assertText('entity language is en', 'Language is placed onto the context.');
$array = array();
$array = [];
foreach ($this->values as $delta => $value) {
$array[] = $delta . ':' . $value['value'];
}
$this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');
// Check the prepare_view steps are invoked.
$display = array(
$display = [
'label' => 'hidden',
'type' => 'field_test_with_prepare_view',
'settings' => array(
'settings' => [
'test_formatter_setting_additional' => $this->randomMachineName(),
),
);
],
];
$build = $items->view($display);
$this->render($build);
$setting = $display['settings']['test_formatter_setting_additional'];
$this->assertNoText($this->label, 'Label was not displayed.');
$this->assertNoText('field_test_entity_display_build_alter', 'Alter not fired.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// View mode: check that display settings specified in the display object
@@ -201,7 +201,7 @@ class DisplayApiTest extends FieldKernelTestBase {
$setting = $this->displayOptions['teaser']['settings']['test_formatter_setting'];
$this->assertText($this->label, 'Label was displayed.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Unknown view mode: check that display settings for 'default' view mode
@@ -211,14 +211,14 @@ class DisplayApiTest extends FieldKernelTestBase {
$setting = $this->displayOptions['default']['settings']['test_formatter_setting'];
$this->assertText($this->label, 'Label was displayed.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
}
/**
* Tests the FieldItemInterface::view() method.
*/
function testFieldItemView() {
public function testFieldItemView() {
// No display settings: check that default display settings are used.
$settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings('field_test_default');
$setting = $settings['test_formatter_setting'];
@@ -226,37 +226,37 @@ class DisplayApiTest extends FieldKernelTestBase {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view();
$this->render($build);
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Check that explicit display settings are used.
$display = array(
$display = [
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $this->randomMachineName(),
),
);
],
];
$setting = $display['settings']['test_formatter_setting_multiple'];
foreach ($this->values as $delta => $value) {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view($display);
$this->render($build);
$this->assertText($setting . '|0:' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|0:' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Check that prepare_view steps are invoked.
$display = array(
$display = [
'type' => 'field_test_with_prepare_view',
'settings' => array(
'settings' => [
'test_formatter_setting_additional' => $this->randomMachineName(),
),
);
],
];
$setting = $display['settings']['test_formatter_setting_additional'];
foreach ($this->values as $delta => $value) {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view($display);
$this->render($build);
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// View mode: check that display settings specified in the field are used.
@@ -265,7 +265,7 @@ class DisplayApiTest extends FieldKernelTestBase {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view('teaser');
$this->render($build);
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Unknown view mode: check that display settings for 'default' view mode
@@ -275,22 +275,22 @@ class DisplayApiTest extends FieldKernelTestBase {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view('unknown_view_mode');
$this->render($build);
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
}
/**
* Tests that the prepareView() formatter method still fires for empty values.
*/
function testFieldEmpty() {
public function testFieldEmpty() {
// Uses \Drupal\field_test\Plugin\Field\FieldFormatter\TestFieldEmptyFormatter.
$display = array(
$display = [
'label' => 'hidden',
'type' => 'field_empty_test',
'settings' => array(
'settings' => [
'test_empty_string' => '**EMPTY FIELD**' . $this->randomMachineName(),
),
);
],
];
// $this->entity is set by the setUp() method and by default contains 4
// numeric values. We only want to test the display of this one field.
$build = $this->entity->get($this->fieldName)->view($display);
@@ -300,7 +300,7 @@ class DisplayApiTest extends FieldKernelTestBase {
$this->assertNoText($display['settings']['test_empty_string']);
// Now remove the values from the test field and retest.
$this->entity->{$this->fieldName} = array();
$this->entity->{$this->fieldName} = [];
$this->entity->save();
$build = $this->entity->get($this->fieldName)->view($display);
$this->render($build);
@@ -20,11 +20,11 @@ class EmailItemTest extends FieldKernelTestBase {
parent::setUp();
// Create an email field storage and field for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_email',
'entity_type' => 'entity_test',
'type' => 'email',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_email',
@@ -33,9 +33,9 @@ class EmailItemTest extends FieldKernelTestBase {
// Create a form display for the default form mode.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent('field_email', array(
->setComponent('field_email', [
'type' => 'email_default',
))
])
->save();
}
@@ -52,7 +52,7 @@ class EmailItemTest extends FieldKernelTestBase {
// Verify entity has been created properly.
$id = $entity->id();
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$this->assertTrue($entity->field_email instanceof FieldItemListInterface, 'Field implements interface.');
$this->assertTrue($entity->field_email[0] instanceof FieldItemInterface, 'Field item implements interface.');
$this->assertEqual($entity->field_email->value, $value);
@@ -65,7 +65,7 @@ class EmailItemTest extends FieldKernelTestBase {
// Read changed entity and assert changed values.
$entity->save();
$entity = entity_load('entity_test', $id);
$entity = EntityTest::load($id);
$this->assertEqual($entity->field_email->value, $new_value);
// Test sample item generation.
@@ -65,10 +65,10 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
// Use Classy theme for testing markup output.
\Drupal::service('theme_handler')->install(['classy']);
\Drupal::service('theme_handler')->setDefault('classy');
$this->config('system.theme')->set('default', 'classy')->save();
$this->installEntitySchema('entity_test');
// Grant the 'view test entity' permission.
$this->installConfig(array('user'));
$this->installConfig(['user']);
Role::load(RoleInterface::ANONYMOUS_ID)
->grantPermission('view test entity')
->save();
@@ -76,16 +76,16 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
// The label formatter rendering generates links, so build the router.
$this->container->get('router.builder')->rebuild();
$this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType, 'default', array(), FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
$this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType, 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
// Set up a field, so that the entity that'll be referenced bubbles up a
// cache tag when rendering it entirely.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'body',
'entity_type' => $this->entityType,
'type' => 'text',
'settings' => array(),
))->save();
'settings' => [],
])->save();
FieldConfig::create([
'entity_type' => $this->entityType,
'bundle' => $this->bundle,
@@ -93,35 +93,35 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
'label' => 'Body',
])->save();
entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent('body', array(
->setComponent('body', [
'type' => 'text_default',
'settings' => array(),
))
'settings' => [],
])
->save();
FilterFormat::create(array(
FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
))->save();
])->save();
// Create the entity to be referenced.
$this->referencedEntity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
$this->referencedEntity->body = array(
->create(['name' => $this->randomMachineName()]);
$this->referencedEntity->body = [
'value' => '<p>Hello, world!</p>',
'format' => 'full_html',
);
];
$this->referencedEntity->save();
// Create another entity to be referenced but do not save it.
$this->unsavedReferencedEntity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
$this->unsavedReferencedEntity->body = array(
->create(['name' => $this->randomMachineName()]);
$this->unsavedReferencedEntity->body = [
'value' => '<p>Hello, unsaved world!</p>',
'format' => 'full_html',
);
];
}
/**
@@ -137,7 +137,7 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
$referencing_entity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
->create(['name' => $this->randomMachineName()]);
$referencing_entity->save();
$referencing_entity->{$field_name}->entity = $this->referencedEntity;
@@ -150,19 +150,32 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
foreach ($formatter_manager->getOptions('entity_reference') as $formatter => $name) {
// Set formatter type for the 'full' view mode.
entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => $formatter,
))
])
->save();
// Invoke entity view.
entity_view($referencing_entity, 'default');
// Verify the un-accessible item still exists.
$this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', array('@name' => $name)));
$this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', ['@name' => $name]));
}
}
/**
* Tests the merging of cache metadata.
*/
public function testCustomCacheTagFormatter() {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$formatter = 'entity_reference_custom_cache_tag';
$build = $this->buildRenderArray([$this->referencedEntity], $formatter);
$renderer->renderRoot($build);
$this->assertTrue(in_array('custom_cache_tag', $build['#cache']['tags']));
}
/**
* Tests the ID formatter.
*/
@@ -198,7 +211,7 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
$this->assertEqual($build[0]['#markup'], 'default | ' . $this->referencedEntity->label() . $expected_rendered_name_field_1 . $expected_rendered_body_field_1, sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
$expected_cache_tags = Cache::mergeTags(\Drupal::entityManager()->getViewBuilder($this->entityType)->getCacheTags(), $this->referencedEntity->getCacheTags());
$expected_cache_tags = Cache::mergeTags($expected_cache_tags, FilterFormat::load('full_html')->getCacheTags());
$this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', array('@formatter' => $formatter)));
$this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', ['@formatter' => $formatter]));
// Test the second field item.
$expected_rendered_name_field_2 = '
@@ -277,6 +290,49 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
$this->assertEqual($actual_occurrences, $expected_occurrences);
}
/**
* Renders the same entity referenced from different places.
*/
public function testEntityReferenceRecursiveProtectionWithManyRenderedEntities() {
$formatter = 'entity_reference_entity_view';
$view_builder = $this->entityManager->getViewBuilder($this->entityType);
// Set the default view mode to use the 'entity_reference_entity_view'
// formatter.
entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent($this->fieldName, [
'type' => $formatter,
])
->save();
$storage = $this->entityManager->getStorage($this->entityType);
/** @var \Drupal\Core\Entity\ContentEntityInterface $referenced_entity */
$referenced_entity = $storage->create(['name' => $this->randomMachineName()]);
$range = range(0, 30);
$referencing_entities = array_map(function () use ($storage, $referenced_entity) {
$referencing_entity = $storage->create([
'name' => $this->randomMachineName(),
$this->fieldName => $referenced_entity,
]);
$referencing_entity->save();
return $referencing_entity;
}, $range);
$build = $view_builder->viewMultiple($referencing_entities, 'default');
$output = $this->render($build);
// The title of entity_test entities is printed twice by default, so we have
// to multiply the formatter's recursive rendering protection limit by 2.
// Additionally, we have to take into account 2 additional occurrences of
// the entity title because we're rendering the full entity, not just the
// reference field.
$expected_occurrences = 30 * 2 + 2;
$actual_occurrences = substr_count($output, $referenced_entity->get('name')->value);
$this->assertEquals($expected_occurrences, $actual_occurrences);
}
/**
* Tests the label formatter.
*/
@@ -295,37 +351,37 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
'max-age' => Cache::PERMANENT,
];
$this->assertEqual($build['#cache'], $expected_field_cacheability, 'The field render array contains the entity access cacheability metadata');
$expected_item_1 = array(
$expected_item_1 = [
'#type' => 'link',
'#title' => $this->referencedEntity->label(),
'#url' => $this->referencedEntity->urlInfo(),
'#options' => $this->referencedEntity->urlInfo()->getOptions(),
'#cache' => array(
'#cache' => [
'contexts' => [
'user.permissions',
],
'tags' => $this->referencedEntity->getCacheTags(),
),
);
],
];
$this->assertEqual($renderer->renderRoot($build[0]), $renderer->renderRoot($expected_item_1), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
$this->assertEqual(CacheableMetadata::createFromRenderArray($build[0]), CacheableMetadata::createFromRenderArray($expected_item_1));
// The second referenced entity is "autocreated", therefore not saved and
// lacking any URL info.
$expected_item_2 = array(
$expected_item_2 = [
'#plain_text' => $this->unsavedReferencedEntity->label(),
'#cache' => array(
'#cache' => [
'contexts' => [
'user.permissions',
],
'tags' => $this->unsavedReferencedEntity->getCacheTags(),
'max-age' => Cache::PERMANENT,
),
);
],
];
$this->assertEqual($build[1], $expected_item_2, sprintf('The render array returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
// Test with the 'link' setting set to FALSE.
$build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, array('link' => FALSE));
$build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, ['link' => FALSE]);
$this->assertEqual($build[0]['#plain_text'], $this->referencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
$this->assertEqual($build[1]['#plain_text'], $this->unsavedReferencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
@@ -336,12 +392,12 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
$field_storage_config->setSetting('target_type', 'entity_test_label');
$field_storage_config->save();
$referenced_entity_with_no_link_template = EntityTestLabel::create(array(
$referenced_entity_with_no_link_template = EntityTestLabel::create([
'name' => $this->randomMachineName(),
));
]);
$referenced_entity_with_no_link_template->save();
$build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, array('link' => TRUE));
$build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, ['link' => TRUE]);
$this->assertEqual($build[0]['#plain_text'], $referenced_entity_with_no_link_template->label(), sprintf('The markup returned by the %s formatter is correct for an entity type with no valid link template.', $formatter));
}
@@ -360,11 +416,11 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
* @return array
* A render array.
*/
protected function buildRenderArray(array $referenced_entities, $formatter, $formatter_options = array()) {
protected function buildRenderArray(array $referenced_entities, $formatter, $formatter_options = []) {
// Create the entity that will have the entity reference field.
$referencing_entity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
->create(['name' => $this->randomMachineName()]);
$items = $referencing_entity->get($this->fieldName);
@@ -374,7 +430,7 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
}
// Build the renderable array for the field.
return $items->view(array('type' => $formatter, 'settings' => $formatter_options));
return $items->view(['type' => $formatter, 'settings' => $formatter_options]);
}
}
@@ -15,6 +15,7 @@ use Drupal\entity_test\Entity\EntityTestStringId;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\node\NodeInterface;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\file\Entity\File;
use Drupal\node\Entity\Node;
@@ -116,7 +117,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$entity->name->value = $this->randomMachineName();
$entity->save();
$entity = entity_load('entity_test', $entity->id());
$entity = EntityTest::load($entity->id());
$this->assertTrue($entity->field_test_taxonomy_term instanceof FieldItemListInterface, 'Field implements interface.');
$this->assertTrue($entity->field_test_taxonomy_term[0] instanceof FieldItemInterface, 'Field item implements interface.');
$this->assertEqual($entity->field_test_taxonomy_term->target_id, $tid);
@@ -174,7 +175,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
// Delete terms so we have nothing to reference and try again
$term->delete();
$term2->delete();
$entity = EntityTest::create(array('name' => $this->randomMachineName()));
$entity = EntityTest::create(['name' => $this->randomMachineName()]);
$entity->save();
// Test the generateSampleValue() method.
@@ -182,6 +183,15 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$entity->field_test_taxonomy_term->generateSampleItems();
$entity->field_test_taxonomy_vocabulary->generateSampleItems();
$this->entityValidateAndSave($entity);
// Tests that setting an integer target ID together with an entity object
// succeeds and does not cause any exceptions. There is no assertion here,
// as the assignment should not throw any exceptions and if it does the
// test will fail.
// @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::setValue().
$user = User::create(['name' => $this->randomString()]);
$user->save();
$entity = EntityTest::create(['user_id' => ['target_id' => (int) $user->id(), 'entity' => $user]]);
}
/**
@@ -212,7 +222,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$entity->name->value = $this->randomMachineName();
$entity->save();
$entity = entity_load('entity_test', $entity->id());
$entity = EntityTest::load($entity->id());
$this->assertTrue($entity->field_test_taxonomy_vocabulary instanceof FieldItemListInterface, 'Field implements interface.');
$this->assertTrue($entity->field_test_taxonomy_vocabulary[0] instanceof FieldItemInterface, 'Field item implements interface.');
$this->assertEqual($entity->field_test_taxonomy_vocabulary->target_id, $referenced_entity_id);
@@ -243,7 +253,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
// Delete terms so we have nothing to reference and try again
$this->vocabulary->delete();
$vocabulary2->delete();
$entity = EntityTest::create(array('name' => $this->randomMachineName()));
$entity = EntityTest::create(['name' => $this->randomMachineName()]);
$entity->save();
}
@@ -252,11 +262,11 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
*/
public function testEntityAutoCreate() {
// The term entity is unsaved here.
$term = Term::create(array(
$term = Term::create([
'name' => $this->randomMachineName(),
'vid' => $this->term->bundle(),
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
));
]);
$entity = EntityTest::create();
// Now assign the unsaved term to the field.
$entity->field_test_taxonomy_term->entity = $term;
@@ -303,22 +313,22 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
*/
public function testSelectionHandlerSettings() {
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'entity_reference',
'settings' => array(
'settings' => [
'target_type' => 'entity_test'
),
));
],
]);
$field_storage->save();
// Do not specify any value for the 'handler' setting in order to verify
// that the default handler with the correct derivative is used.
$field = FieldConfig::create(array(
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'entity_test',
));
]);
$field->save();
$field = FieldConfig::load($field->id());
$this->assertEqual($field->getSetting('handler'), 'default:entity_test');
@@ -349,11 +359,11 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
*/
public function testAutocreateValidation() {
// The term entity is unsaved here.
$term = Term::create(array(
$term = Term::create([
'name' => $this->randomMachineName(),
'vid' => $this->term->bundle(),
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
));
]);
$entity = EntityTest::create([
'field_test_taxonomy_term' => [
'entity' => $term,
@@ -385,7 +395,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$node = Node::create([
'title' => $title,
'type' => 'node',
'status' => NODE_NOT_PUBLISHED,
'status' => NodeInterface::NOT_PUBLISHED,
]);
$entity = EntityTest::create([
@@ -409,14 +419,14 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$unsaved_unpublished_node = Node::create([
'title' => $unsaved_unpublished_node_title,
'type' => 'node',
'status' => NODE_NOT_PUBLISHED,
'status' => NodeInterface::NOT_PUBLISHED,
]);
$saved_unpublished_node_title = $this->randomString();
$saved_unpublished_node = Node::create([
'title' => $saved_unpublished_node_title,
'type' => 'node',
'status' => NODE_NOT_PUBLISHED,
'status' => NodeInterface::NOT_PUBLISHED,
]);
$saved_unpublished_node->save();
@@ -424,7 +434,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$saved_published_node = Node::create([
'title' => $saved_published_node_title,
'type' => 'node',
'status' => NODE_PUBLISHED,
'status' => NodeInterface::PUBLISHED,
]);
$saved_published_node->save();
@@ -2,6 +2,8 @@
namespace Drupal\Tests\field\Kernel\EntityReference\Views;
use Drupal\entity_test\Entity\EntityTestMulChanged;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\Entity\EntityTestMul;
@@ -25,12 +27,14 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
*
* @var array
*/
public static $testViews = array(
public static $testViews = [
'test_entity_reference_entity_test_view',
'test_entity_reference_entity_test_view_long',
'test_entity_reference_reverse_entity_test_view',
'test_entity_reference_entity_test_mul_view',
'test_entity_reference_reverse_entity_test_mul_view',
);
'test_entity_reference_group_by_empty_relationships',
];
/**
* Modules to install.
@@ -44,7 +48,7 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
*
* @var array
*/
protected $entities = array();
protected $entities = [];
/**
* {@inheritdoc}
@@ -55,6 +59,7 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
$this->installEntitySchema('user');
$this->installEntitySchema('entity_test');
$this->installEntitySchema('entity_test_mul');
$this->installEntitySchema('entity_test_mul_changed');
// Create reference from entity_test to entity_test_mul.
$this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_data', 'field_test_data', 'entity_test_mul');
@@ -62,7 +67,16 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
// Create reference from entity_test_mul to entity_test.
$this->createEntityReferenceField('entity_test_mul', 'entity_test_mul', 'field_data_test', 'field_data_test', 'entity_test');
ViewTestData::createTestViews(get_class($this), array('entity_reference_test_views'));
// Create another field for testing with a long name. So it's storage name
// will become hashed. Use entity_test_mul_changed, so the resulting field
// tables created will be greater than 48 chars long.
// @see \Drupal\Core\Entity\Sql\DefaultTableMapping::generateFieldTableName()
$this->createEntityReferenceField('entity_test_mul_changed', 'entity_test_mul_changed', 'field_test_data_with_a_long_name', 'field_test_data_with_a_long_name', 'entity_test');
// Create reference from entity_test_mul to entity_test cardinality: infinite.
$this->createEntityReferenceField('entity_test_mul', 'entity_test_mul', 'field_data_test_unlimited', 'field_data_test_unlimited', 'entity_test', 'default', [], FieldStorageConfig::CARDINALITY_UNLIMITED);
ViewTestData::createTestViews(get_class($this), ['entity_reference_test_views']);
}
/**
@@ -124,7 +138,6 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
// Test that the correct relationship entity is on the row.
$this->assertEqual($row->_relationship_entities['field_test_data']->id(), 1);
$this->assertEqual($row->_relationship_entities['field_test_data']->bundle(), 'entity_test_mul');
}
// Check the backwards reference view.
@@ -225,4 +238,99 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
}
}
/**
* Tests views data generated for relationship.
*
* @see entity_reference_field_views_data()
*/
public function testDataTableRelationshipWithLongFieldName() {
// Create some test entities which link each other.
$referenced_entity = EntityTest::create();
$referenced_entity->save();
$entity = EntityTestMulChanged::create();
$entity->field_test_data_with_a_long_name->target_id = $referenced_entity->id();
$entity->save();
$this->entities[] = $entity;
$entity = EntityTestMulChanged::create();
$entity->field_test_data_with_a_long_name->target_id = $referenced_entity->id();
$entity->save();
$this->entities[] = $entity;
Views::viewsData()->clear();
// Check an actual test view.
$view = Views::getView('test_entity_reference_entity_test_view_long');
$this->executeView($view);
/** @var \Drupal\views\ResultRow $row */
foreach ($view->result as $index => $row) {
// Check that the actual ID of the entity is the expected one.
$this->assertEqual($row->id, $this->entities[$index]->id());
// Also check that we have the correct result entity.
$this->assertEqual($row->_entity->id(), $this->entities[$index]->id());
// Test the forward relationship.
//$this->assertEqual($row->entity_test_entity_test_mul__field_data_test_id, 1);
// Test that the correct relationship entity is on the row.
$this->assertEqual($row->_relationship_entities['field_test_data_with_a_long_name']->id(), 1);
$this->assertEqual($row->_relationship_entities['field_test_data_with_a_long_name']->bundle(), 'entity_test');
}
}
/**
* Tests group by with optional and empty relationship.
*/
public function testGroupByWithEmptyRelationships() {
$entities = [];
// Create 4 entities with name1 and 3 entities with name2.
for ($i = 1; $i <= 4; $i++) {
$entity = [
'name' => 'name' . $i,
];
$entity = EntityTest::create($entity);
$entities[] = $entity;
$entity->save();
}
$entity = EntityTestMul::create([
'name' => 'name1',
]);
$entity->field_data_test_unlimited = [
['target_id' => $entities[0]->id()],
['target_id' => $entities[1]->id()],
['target_id' => $entities[2]->id()],
];
$entity->save();
$entity = EntityTestMul::create([
'name' => 'name2',
]);
$entity->field_data_test_unlimited = [
['target_id' => $entities[0]->id()],
['target_id' => $entities[1]->id()],
];
$entity->save();
$entity = EntityTestMul::create([
'name' => 'name3',
]);
$entity->field_data_test_unlimited->target_id = $entities[0]->id();
$entity->save();
$view = Views::getView('test_entity_reference_group_by_empty_relationships');
$this->executeView($view);
$this->assertCount(4, $view->result);
// First three results should contain a reference from EntityTestMul.
$this->assertNotEmpty($view->getStyle()->getField(0, 'name_2'));
$this->assertNotEmpty($view->getStyle()->getField(1, 'name_2'));
$this->assertNotEmpty($view->getStyle()->getField(2, 'name_2'));
// Fourth result has no reference from EntityTestMul hence the output for
// should be empty.
$this->assertEqual('', $view->getStyle()->getField(3, 'name_2'));
}
}
@@ -23,7 +23,7 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
/**
* Test rendering fields with EntityDisplay build().
*/
function testEntityDisplayBuild() {
public function testEntityDisplayBuild() {
$this->createFieldWithStorage('_2');
$entity_type = 'entity_test';
@@ -42,23 +42,23 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
$display = entity_get_display($entity_type, $entity->bundle(), 'full');
$formatter_setting = $this->randomMachineName();
$display_options = array(
$display_options = [
'label' => 'above',
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $formatter_setting,
),
);
],
];
$display->setComponent($this->fieldTestData->field_name, $display_options);
$formatter_setting_2 = $this->randomMachineName();
$display_options_2 = array(
$display_options_2 = [
'label' => 'above',
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $formatter_setting_2,
),
);
],
];
$display->setComponent($this->fieldTestData->field_name_2, $display_options_2);
// View all fields.
@@ -94,13 +94,13 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
// Multiple formatter.
$entity = clone($entity_init);
$formatter_setting = $this->randomMachineName();
$display->setComponent($this->fieldTestData->field_name, array(
$display->setComponent($this->fieldTestData->field_name, [
'label' => 'above',
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $formatter_setting,
),
));
],
]);
$content = $display->build($entity);
$this->render($content);
$expected_output = $formatter_setting;
@@ -112,13 +112,13 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
// Test a formatter that uses hook_field_formatter_prepare_view().
$entity = clone($entity_init);
$formatter_setting = $this->randomMachineName();
$display->setComponent($this->fieldTestData->field_name, array(
$display->setComponent($this->fieldTestData->field_name, [
'label' => 'above',
'type' => 'field_test_with_prepare_view',
'settings' => array(
'settings' => [
'test_formatter_setting_additional' => $formatter_setting,
),
));
],
]);
$content = $display->build($entity);
$this->render($content);
foreach ($values as $delta => $value) {
@@ -133,21 +133,21 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
/**
* Tests rendering fields with EntityDisplay::buildMultiple().
*/
function testEntityDisplayViewMultiple() {
public function testEntityDisplayViewMultiple() {
// Use a formatter that has a prepareView() step.
$display = entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($this->fieldTestData->field_name, array(
->setComponent($this->fieldTestData->field_name, [
'type' => 'field_test_with_prepare_view',
));
]);
// Create two entities.
$entity1 = EntityTest::create(array('id' => 1, 'type' => 'entity_test'));
$entity1 = EntityTest::create(['id' => 1, 'type' => 'entity_test']);
$entity1->{$this->fieldTestData->field_name}->setValue($this->_generateTestFieldValues(1));
$entity2 = EntityTest::create(array('id' => 2, 'type' => 'entity_test'));
$entity2 = EntityTest::create(['id' => 2, 'type' => 'entity_test']);
$entity2->{$this->fieldTestData->field_name}->setValue($this->_generateTestFieldValues(1));
// Run buildMultiple(), and check that the entities come out as expected.
$display->buildMultiple(array($entity1, $entity2));
$display->buildMultiple([$entity1, $entity2]);
$item1 = $entity1->{$this->fieldTestData->field_name}[0];
$this->assertEqual($item1->additional_formatter_value, $item1->value + 1, 'Entity 1 ran through the prepareView() formatter method.');
$item2 = $entity2->{$this->fieldTestData->field_name}[0];
@@ -160,9 +160,9 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
* Complements unit test coverage in
* \Drupal\Tests\Core\Entity\Sql\SqlContentEntityStorageTest.
*/
function testEntityCache() {
public function testEntityCache() {
// Initialize random values and a test entity.
$entity_init = EntityTest::create(array('type' => $this->fieldTestData->field->getTargetBundle()));
$entity_init = EntityTest::create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$values = $this->_generateTestFieldValues($this->fieldTestData->field_storage->getCardinality());
// Non-cacheable entity type.
@@ -185,9 +185,9 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array(
->create([
'type' => $entity_type,
));
]);
// Check that no initial cache entry is present.
$cid = "values:$entity_type:" . $entity->id();
@@ -243,15 +243,15 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
* This could be much more thorough, but it does verify that the correct
* widgets show up.
*/
function testEntityFormDisplayBuildForm() {
public function testEntityFormDisplayBuildForm() {
$this->createFieldWithStorage('_2');
$entity_type = 'entity_test';
$entity = entity_create($entity_type, array('id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()));
$entity = entity_create($entity_type, ['id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()]);
// Test generating widgets for all fields.
$display = entity_get_form_display($entity_type, $this->fieldTestData->field->getTargetBundle(), 'default');
$form = array();
$form = [];
$form_state = new FormState();
$display->buildForm($entity, $form, $form_state);
@@ -273,7 +273,7 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
$display->removeComponent($name);
}
}
$form = array();
$form = [];
$form_state = new FormState();
$display->buildForm($entity, $form, $form_state);
@@ -288,24 +288,24 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
/**
* Tests \Drupal\Core\Entity\Display\EntityFormDisplayInterface::extractFormValues().
*/
function testEntityFormDisplayExtractFormValues() {
public function testEntityFormDisplayExtractFormValues() {
$this->createFieldWithStorage('_2');
$entity_type = 'entity_test';
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()));
->create(['id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()]);
// Build the form for all fields.
$display = entity_get_form_display($entity_type, $this->fieldTestData->field->getTargetBundle(), 'default');
$form = array();
$form = [];
$form_state = new FormState();
$display->buildForm($entity_init, $form, $form_state);
// Simulate incoming values.
// First field.
$values = array();
$weights = array();
$values = [];
$weights = [];
for ($delta = 0; $delta < $this->fieldTestData->field_storage->getCardinality(); $delta++) {
$values[$delta]['value'] = mt_rand(1, 127);
// Assign random weight.
@@ -318,8 +318,8 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
// Leave an empty value. 'field_test' fields are empty if empty().
$values[1]['value'] = 0;
// Second field.
$values_2 = array();
$weights_2 = array();
$values_2 = [];
$weights_2 = [];
for ($delta = 0; $delta < $this->fieldTestData->field_storage_2->getCardinality(); $delta++) {
$values_2[$delta]['value'] = mt_rand(1, 127);
// Assign random weight.
@@ -345,17 +345,17 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
asort($weights);
asort($weights_2);
$expected_values = array();
$expected_values_2 = array();
$expected_values = [];
$expected_values_2 = [];
foreach ($weights as $key => $value) {
if ($key != 1) {
$expected_values[] = array('value' => $values[$key]['value']);
$expected_values[] = ['value' => $values[$key]['value']];
}
}
$this->assertIdentical($entity->{$this->fieldTestData->field_name}->getValue(), $expected_values, 'Submit filters empty values');
foreach ($weights_2 as $key => $value) {
if ($key != 1) {
$expected_values_2[] = array('value' => $values_2[$key]['value']);
$expected_values_2[] = ['value' => $values_2[$key]['value']];
}
}
$this->assertIdentical($entity->{$this->fieldTestData->field_name_2}->getValue(), $expected_values_2, 'Submit filters empty values');
@@ -368,10 +368,10 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
}
$entity = clone($entity_init);
$display->extractFormValues($entity, $form, $form_state);
$expected_values_2 = array();
$expected_values_2 = [];
foreach ($weights_2 as $key => $value) {
if ($key != 1) {
$expected_values_2[] = array('value' => $values_2[$key]['value']);
$expected_values_2[] = ['value' => $values_2[$key]['value']];
}
}
$this->assertTrue($entity->{$this->fieldTestData->field_name}->isEmpty(), 'The first field is empty in the entity object');
@@ -24,14 +24,14 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
* Works independently of the underlying field storage backend. Inserts or
* updates random field data and then loads and verifies the data.
*/
function testFieldAttachSaveLoad() {
public function testFieldAttachSaveLoad() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
$cardinality = $this->fieldTestData->field_storage->getCardinality();
// TODO : test empty values filtering and "compression" (store consecutive deltas).
// Preparation: create three revisions and store them in $revision array.
$values = array();
$values = [];
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create();
@@ -54,17 +54,17 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
$this->assertEqual(count($entity->{$this->fieldTestData->field_name}), $cardinality, 'Current revision: expected number of values');
for ($delta = 0; $delta < $cardinality; $delta++) {
// The field value loaded matches the one inserted or updated.
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$current_revision][$delta]['value'], format_string('Current revision: expected value %delta was found.', array('%delta' => $delta)));
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$current_revision][$delta]['value'], format_string('Current revision: expected value %delta was found.', ['%delta' => $delta]));
}
// Confirm each revision loads the correct data.
foreach (array_keys($values) as $revision_id) {
$entity = $storage->loadRevision($revision_id);
// Number of values per field loaded equals the field cardinality.
$this->assertEqual(count($entity->{$this->fieldTestData->field_name}), $cardinality, format_string('Revision %revision_id: expected number of values.', array('%revision_id' => $revision_id)));
$this->assertEqual(count($entity->{$this->fieldTestData->field_name}), $cardinality, format_string('Revision %revision_id: expected number of values.', ['%revision_id' => $revision_id]));
for ($delta = 0; $delta < $cardinality; $delta++) {
// The field value loaded matches the one inserted or updated.
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$revision_id][$delta]['value'], format_string('Revision %revision_id: expected value %delta was found.', array('%revision_id' => $revision_id, '%delta' => $delta)));
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$revision_id][$delta]['value'], format_string('Revision %revision_id: expected value %delta was found.', ['%revision_id' => $revision_id, '%delta' => $delta]));
}
}
}
@@ -72,32 +72,32 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test the 'multiple' load feature.
*/
function testFieldAttachLoadMultiple() {
public function testFieldAttachLoadMultiple() {
$entity_type = 'entity_test_rev';
// Define 2 bundles.
$bundles = array(
$bundles = [
1 => 'test_bundle_1',
2 => 'test_bundle_2',
);
];
entity_test_create_bundle($bundles[1]);
entity_test_create_bundle($bundles[2]);
// Define 3 fields:
// - field_1 is in bundle_1 and bundle_2,
// - field_2 is in bundle_1,
// - field_3 is in bundle_2.
$field_bundles_map = array(
1 => array(1, 2),
2 => array(1),
3 => array(2),
);
$field_bundles_map = [
1 => [1, 2],
2 => [1],
3 => [2],
];
for ($i = 1; $i <= 3; $i++) {
$field_names[$i] = 'field_' . $i;
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $field_names[$i],
'entity_type' => $entity_type,
'type' => 'test_field',
));
]);
$field_storage->save();
$field_ids[$i] = $field_storage->uuid();
foreach ($field_bundles_map[$i] as $bundle) {
@@ -113,14 +113,14 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
foreach ($bundles as $index => $bundle) {
$entities[$index] = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => $index, 'revision_id' => $index, 'type' => $bundle));
->create(['id' => $index, 'revision_id' => $index, 'type' => $bundle]);
$entity = clone($entities[$index]);
foreach ($field_names as $field_name) {
if (!$entity->hasField($field_name)) {
continue;
}
$values[$index][$field_name] = mt_rand(1, 127);
$entity->$field_name->setValue(array('value' => $values[$index][$field_name]));
$entity->$field_name->setValue(['value' => $values[$index][$field_name]]);
}
$entity->enforceIsnew();
$entity->save();
@@ -136,7 +136,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
continue;
}
// The field value loaded matches the one inserted.
$this->assertEqual($entity->{$field_name}->value, $values[$index][$field_name], format_string('Entity %index: expected value was found.', array('%index' => $index)));
$this->assertEqual($entity->{$field_name}->value, $values[$index][$field_name], format_string('Entity %index: expected value was found.', ['%index' => $index]));
}
}
}
@@ -144,13 +144,13 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Tests insert and update with empty or NULL fields.
*/
function testFieldAttachSaveEmptyData() {
public function testFieldAttachSaveEmptyData() {
$entity_type = 'entity_test';
$this->createFieldWithStorage('', $entity_type);
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 1));
->create(['id' => 1]);
// Insert: Field is NULL.
$entity = clone $entity_init;
@@ -184,7 +184,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Update: Field is empty array. Data should be wiped.
$entity = clone($entity_init);
$entity->{$this->fieldTestData->field_name} = array();
$entity->{$this->fieldTestData->field_name} = [];
$entity = $this->entitySaveReload($entity);
$this->assertTrue($entity->{$this->fieldTestData->field_name}->isEmpty(), 'Update: empty array removes existing values');
}
@@ -192,7 +192,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test insert with empty or NULL fields, with default value.
*/
function testFieldAttachSaveEmptyDataDefaultValue() {
public function testFieldAttachSaveEmptyDataDefaultValue() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
@@ -203,7 +203,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Verify that fields are populated with default values.
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 1, 'revision_id' => 1));
->create(['id' => 1, 'revision_id' => 1]);
$default = field_test_default_value($entity_init, $this->fieldTestData->field);
$this->assertEqual($entity_init->{$this->fieldTestData->field_name}->getValue(), $default, 'Default field value correctly populated.');
@@ -215,24 +215,24 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
$this->assertTrue($entity->{$this->fieldTestData->field_name}->isEmpty(), 'Insert: NULL field results in no value saved');
// Verify that prepopulated field values are not overwritten by defaults.
$value = array(array('value' => $default[0]['value'] - mt_rand(1, 127)));
$value = [['value' => $default[0]['value'] - mt_rand(1, 127)]];
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $entity_init->bundle(), $this->fieldTestData->field_name => $value));
->create(['type' => $entity_init->bundle(), $this->fieldTestData->field_name => $value]);
$this->assertEqual($entity->{$this->fieldTestData->field_name}->getValue(), $value, 'Prepopulated field value correctly maintained.');
}
/**
* Test entity deletion.
*/
function testFieldAttachDelete() {
public function testFieldAttachDelete() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
$cardinality = $this->fieldTestData->field_storage->getCardinality();
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $this->fieldTestData->field->getTargetBundle()));
$vids = array();
->create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$vids = [];
// Create revision 0
$values = $this->_generateTestFieldValues($cardinality);
@@ -261,7 +261,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Delete revision 1, confirm the other two still load.
$controller->deleteRevision($vids[1]);
$controller->resetCache();
foreach (array(0, 2) as $key) {
foreach ([0, 2] as $key) {
$vid = $vids[$key];
$revision = $controller->loadRevision($vid);
$this->assertEqual(count($revision->{$this->fieldTestData->field_name}), $cardinality, "The test entity revision $vid has $cardinality values.");
@@ -275,7 +275,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Delete all field data, confirm nothing loads
$entity->delete();
$controller->resetCache();
foreach (array(0, 1, 2) as $vid) {
foreach ([0, 1, 2] as $vid) {
$revision = $controller->loadRevision($vid);
$this->assertFalse($revision);
}
@@ -285,7 +285,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test entity_bundle_create().
*/
function testEntityCreateBundle() {
public function testEntityCreateBundle() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
$cardinality = $this->fieldTestData->field_storage->getCardinality();
@@ -301,7 +301,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Save an entity with data in the field.
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $this->fieldTestData->field->getTargetBundle()));
->create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$values = $this->_generateTestFieldValues($cardinality);
$entity->{$this->fieldTestData->field_name} = $values;
@@ -313,7 +313,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test entity_bundle_delete().
*/
function testEntityDeleteBundle() {
public function testEntityDeleteBundle() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
@@ -327,27 +327,27 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Create a second field for the test bundle
$field_name = Unicode::strtolower($this->randomMachineName() . '_field_name');
$field_storage = array(
$field_storage = [
'field_name' => $field_name,
'entity_type' => $entity_type,
'type' => 'test_field',
'cardinality' => 1,
);
];
FieldStorageConfig::create($field_storage)->save();
$field = array(
$field = [
'field_name' => $field_name,
'entity_type' => $entity_type,
'bundle' => $this->fieldTestData->field->getTargetBundle(),
'label' => $this->randomMachineName() . '_label',
'description' => $this->randomMachineName() . '_description',
'weight' => mt_rand(0, 127),
);
];
FieldConfig::create($field)->save();
// Save an entity with data for both fields
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $this->fieldTestData->field->getTargetBundle()));
->create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$values = $this->_generateTestFieldValues($this->fieldTestData->field_storage->getCardinality());
$entity->{$this->fieldTestData->field_name} = $values;
$entity->{$field_name} = $this->_generateTestFieldValues(1);
@@ -12,6 +12,8 @@ use Drupal\field\Entity\FieldConfig;
/**
* Create field entities by attaching fields to entities.
*
* @coversDefaultClass \Drupal\Core\Field\FieldConfigBase
*
* @group field
*/
class FieldCrudTest extends FieldKernelTestBase {
@@ -37,21 +39,21 @@ class FieldCrudTest extends FieldKernelTestBase {
*/
protected $fieldDefinition;
function setUp() {
public function setUp() {
parent::setUp();
$this->fieldStorageDefinition = array(
$this->fieldStorageDefinition = [
'field_name' => Unicode::strtolower($this->randomMachineName()),
'entity_type' => 'entity_test',
'type' => 'test_field',
);
];
$this->fieldStorage = FieldStorageConfig::create($this->fieldStorageDefinition);
$this->fieldStorage->save();
$this->fieldDefinition = array(
$this->fieldDefinition = [
'field_name' => $this->fieldStorage->getName(),
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
);
];
}
// TODO : test creation with
@@ -63,11 +65,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test the creation of a field.
*/
function testCreateField() {
// Set a state flag so that field_test.module knows to add an in-memory
// constraint for this field.
\Drupal::state()->set('field_test_add_constraint', $this->fieldStorage->getName());
/** @var \Drupal\Core\Field\FieldConfigInterface $field */
public function testCreateField() {
$field = FieldConfig::create($this->fieldDefinition);
$field->save();
@@ -100,17 +98,6 @@ class FieldCrudTest extends FieldKernelTestBase {
// Check that the denormalized 'field_type' was properly written.
$this->assertEqual($config['field_type'], $this->fieldStorageDefinition['type']);
// Test constraints are applied. A Range constraint is added dynamically to
// limit the field to values between 0 and 32.
// @see field_test_entity_bundle_field_info_alter()
$this->doFieldValidationTests();
// Test FieldConfigBase::setPropertyConstraints().
\Drupal::state()->set('field_test_set_constraint', $this->fieldStorage->getName());
\Drupal::state()->set('field_test_add_constraint', FALSE);
\Drupal::entityManager()->clearCachedFieldDefinitions();
$this->doFieldValidationTests();
// Guarantee that the field/bundle combination is unique.
try {
FieldConfig::create($this->fieldDefinition)->save();
@@ -133,6 +120,81 @@ class FieldCrudTest extends FieldKernelTestBase {
// TODO: test other failures.
}
/**
* Tests setting and adding property constraints to a configurable field.
*
* @covers ::setPropertyConstraints
* @covers ::addPropertyConstraints
*/
public function testFieldPropertyConstraints() {
$field = FieldConfig::create($this->fieldDefinition);
$field->save();
$field_name = $this->fieldStorage->getName();
// Test that constraints are applied to configurable fields. A TestField and
// a Range constraint are added dynamically to limit the field to values
// between 0 and 32.
// @see field_test_entity_bundle_field_info_alter()
\Drupal::state()->set('field_test_constraint', $field_name);
// Clear the field definitions cache so the new constraints added by
// field_test_entity_bundle_field_info_alter() are taken into consideration.
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
// Test the newly added property constraints in the same request as when the
// caches were cleared. This will test the field definitions that are stored
// in the static cache of
// \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions().
$this->doFieldPropertyConstraintsTests();
// In order to test a real-world scenario where the property constraints are
// only stored in the persistent cache of
// \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions(), we need to
// simulate a new request by removing the 'entity_field.manager' service,
// thus forcing it to be re-initialized without static caches.
\Drupal::getContainer()->set('entity_field.manager', NULL);
// This will test the field definitions that are stored in the persistent
// cache by \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions().
$this->doFieldPropertyConstraintsTests();
}
/**
* Tests configurable field validation.
*
* @see field_test_entity_bundle_field_info_alter()
*/
protected function doFieldPropertyConstraintsTests() {
$field_name = $this->fieldStorage->getName();
// Check that a valid value (not -2 and between 0 and 32) doesn't trigger
// any violation.
$entity = EntityTest::create();
$entity->set($field_name, 1);
$violations = $entity->validate();
$this->assertCount(0, $violations, 'No violations found when in-range value passed.');
// Check that a value that is specifically restricted triggers both
// violations.
$entity->set($field_name, -2);
$violations = $entity->validate();
$this->assertCount(2, $violations, 'Two violations found when using a null and outside the range value.');
$this->assertEquals($field_name . '.0.value', $violations[0]->getPropertyPath());
$this->assertEquals(t('%name does not accept the value @value.', ['%name' => $field_name, '@value' => -2]), $violations[0]->getMessage());
$this->assertEquals($field_name . '.0.value', $violations[1]->getPropertyPath());
$this->assertEquals(t('This value should be %limit or more.', ['%limit' => 0]), $violations[1]->getMessage());
// Check that a value that is not specifically restricted but outside the
// range triggers the expected violation.
$entity->set($field_name, 33);
$violations = $entity->validate();
$this->assertCount(1, $violations, 'Violations found when using value outside the range.');
$this->assertEquals($field_name . '.0.value', $violations[0]->getPropertyPath());
$this->assertEquals(t('This value should be %limit or less.', ['%limit' => 32]), $violations[0]->getMessage());
}
/**
* Test creating a field with custom storage set.
*/
@@ -174,7 +236,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test reading back a field definition.
*/
function testReadField() {
public function testReadField() {
FieldConfig::create($this->fieldDefinition)->save();
// Read the field back.
@@ -187,7 +249,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test the update of a field.
*/
function testUpdateField() {
public function testUpdateField() {
FieldConfig::create($this->fieldDefinition)->save();
// Check that basic changes are saved.
@@ -209,7 +271,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test the deletion of a field.
*/
function testDeleteField() {
public function testDeleteField() {
// TODO: Test deletion of the data stored in the field also.
// Need to check that data for a 'deleted' field / storage doesn't get loaded
// Need to check data marked deleted is cleaned on cron (not implemented yet...)
@@ -223,12 +285,12 @@ class FieldCrudTest extends FieldKernelTestBase {
FieldConfig::create($another_field_definition)->save();
// Test that the first field is not deleted, and then delete it.
$field = current(entity_load_multiple_by_properties('field_config', array('entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE)));
$field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
$this->assertTrue(!empty($field) && empty($field->deleted), 'A new field is not marked for deletion.');
$field->delete();
// Make sure the field is marked as deleted when it is specifically loaded.
$field = current(entity_load_multiple_by_properties('field_config', array('entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE)));
$field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
$this->assertTrue($field->isDeleted(), 'A deleted field is marked for deletion.');
// Try to load the field normally and make sure it does not show up.
@@ -243,7 +305,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Tests the cross deletion behavior between field storages and fields.
*/
function testDeleteFieldCrossDeletion() {
public function testDeleteFieldCrossDeletion() {
$field_definition_2 = $this->fieldDefinition;
$field_definition_2['bundle'] .= '_another_bundle';
entity_test_create_bundle($field_definition_2['bundle']);
@@ -276,28 +338,8 @@ class FieldCrudTest extends FieldKernelTestBase {
$field->save();
$field_2 = FieldConfig::create($field_definition_2);
$field_2->save();
$this->container->get('entity.manager')->getStorage('field_config')->delete(array($field, $field_2));
$this->container->get('entity.manager')->getStorage('field_config')->delete([$field, $field_2]);
$this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));
}
/**
* Tests configurable field validation.
*
* @see field_test_entity_bundle_field_info_alter()
*/
protected function doFieldValidationTests() {
$entity = EntityTest::create();
$entity->set($this->fieldStorage->getName(), 1);
$violations = $entity->validate();
$this->assertEqual(count($violations), 0, 'No violations found when in-range value passed.');
$entity->set($this->fieldStorage->getName(), 33);
$violations = $entity->validate();
$this->assertEqual(count($violations), 1, 'Violations found when using value outside the range.');
$this->assertEqual($violations[0]->getPropertyPath(), $this->fieldStorage->getName() . '.0.value');
$this->assertEqual($violations[0]->getMessage(), t('This value should be %limit or less.', [
'%limit' => 32,
]));
}
}

Some files were not shown because too many files have changed in this diff Show More