ManageFieldsTest.php 30.6 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\field_ui\Tests\ManageFieldsTest.
6 7 8 9
 */

namespace Drupal\field_ui\Tests;

10
use Drupal\Component\Utility\SafeMarkup;
11 12
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Language\LanguageInterface;
13
use Drupal\entity_reference\Tests\EntityReferenceTestTrait;
14
use Drupal\field\Entity\FieldConfig;
15
use Drupal\field\Entity\FieldStorageConfig;
16
use Drupal\simpletest\WebTestBase;
17
use Drupal\taxonomy\Entity\Vocabulary;
18

19
/**
20 21 22
 * Tests the Field UI "Manage fields" screen.
 *
 * @group field_ui
23
 */
24
class ManageFieldsTest extends WebTestBase {
25

26
  use FieldUiTestTrait;
27
  use EntityReferenceTestTrait;
28 29

  /**
30
   * Modules to install.
31 32 33
   *
   * @var array
   */
34
  public static $modules = array('node', 'field_ui', 'field_test', 'taxonomy', 'image', 'block');
35

36
  /**
37
   * The ID of the custom content type created for testing.
38
   *
39
   * @var string
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
   */
  protected $contentType;

  /**
   * The label for a random field to be created for testing.
   *
   * @var string
   */
  protected $fieldLabel;

  /**
   * The input name of a random field to be created for testing.
   *
   * @var string
   */
  protected $fieldNameInput;

  /**
   * The name of a random field to be created for testing.
   *
   * @var string
   */
  protected $fieldName;

64 65 66
  /**
   * {@inheritdoc}
   */
67
  protected function setUp() {
68
    parent::setUp();
69

70
    $this->drupalPlaceBlock('system_breadcrumb_block');
71 72
    $this->drupalPlaceBlock('local_actions_block');
    $this->drupalPlaceBlock('local_tasks_block');
73

74 75 76 77 78 79 80
    // Create a test user.
    $admin_user = $this->drupalCreateUser(array('access content', 'administer content types', 'administer node fields', 'administer node form display', 'administer node display', 'administer taxonomy', 'administer taxonomy_term fields', 'administer taxonomy_term display', 'administer users', 'administer account settings', 'administer user display', 'bypass node access'));
    $this->drupalLogin($admin_user);

    // Create content type, with underscores.
    $type_name = strtolower($this->randomMachineName(8)) . '_test';
    $type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name));
81
    $this->contentType = $type->id();
82

83 84
    // Create random field name with markup to test escaping.
    $this->fieldLabel = '<em>' . $this->randomMachineName(8) . '</em>';
85 86
    $this->fieldNameInput =  strtolower($this->randomMachineName(8));
    $this->fieldName = 'field_'. $this->fieldNameInput;
87 88 89 90 91 92

    // Create Basic page and Article node types.
    $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
    $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));

    // Create a vocabulary named "Tags".
93
    $vocabulary = Vocabulary::create(array(
94
      'name' => 'Tags',
95
      'vid' => 'tags',
96
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
97
    ));
98
    $vocabulary->save();
99

100 101 102 103 104 105
    $handler_settings = array(
      'target_bundles' => array(
        $vocabulary->id() => $vocabulary->id(),
      ),
    );
    $this->createEntityReferenceField('node', 'article', 'field_' . $vocabulary->id(), 'Tags', 'taxonomy_term', 'default', $handler_settings);
106 107 108 109

    entity_get_form_display('node', 'article', 'default')
      ->setComponent('field_' . $vocabulary->id())
      ->save();
110 111 112 113 114 115 116 117 118 119 120 121 122
  }

  /**
   * Runs the field CRUD tests.
   *
   * In order to act on the same fields, and not create the fields over and over
   * again the following tests create, update and delete the same fields.
   */
  function testCRUDFields() {
    $this->manageFieldsPage();
    $this->createField();
    $this->updateField();
    $this->addExistingField();
123
    $this->cardinalitySettings();
124
    $this->fieldListAdminPage();
125
    $this->deleteField();
126
    $this->addPersistentFieldStorage();
127 128 129 130
  }

  /**
   * Tests the manage fields page.
131 132 133
   *
   * @param string $type
   *   (optional) The name of a content type.
134
   */
135
  function manageFieldsPage($type = '') {
136
    $type = empty($type) ? $this->contentType : $type;
137
    $this->drupalGet('admin/structure/types/manage/' . $type . '/fields');
138 139 140 141 142 143 144 145 146
    // Check all table columns.
    $table_headers = array(
      t('Label'),
      t('Machine name'),
      t('Field type'),
      t('Operations'),
    );
    foreach ($table_headers as $table_header) {
      // We check that the label appear in the table headings.
147
      $this->assertRaw($table_header . '</th>', format_string('%table_header table header was found.', array('%table_header' => $table_header)));
148 149
    }

150 151
    // Test the "Add field" action link.
    $this->assertLink('Add field');
152

153
    // Assert entity operations for all fields.
154 155 156
    $number_of_links = 3;
    $number_of_links_found = 0;
    $operation_links = $this->xpath('//ul[@class = "dropbutton"]/li/a');
157
    $url = base_path() . "admin/structure/types/manage/$type/fields/node.$type.body";
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

    foreach ($operation_links as $link) {
      switch ($link['title']) {
        case 'Edit field settings.':
          $this->assertIdentical($url, (string) $link['href']);
          $number_of_links_found++;
          break;
        case 'Edit storage settings.':
          $this->assertIdentical("$url/storage", (string) $link['href']);
          $number_of_links_found++;
          break;
        case 'Delete field.':
          $this->assertIdentical("$url/delete", (string) $link['href']);
          $number_of_links_found++;
          break;
      }
    }

    $this->assertEqual($number_of_links, $number_of_links_found);
177 178 179 180 181
  }

  /**
   * Tests adding a new field.
   *
182 183
   * @todo Assert properties can bet set in the form and read back in
   * $field_storage and $fields.
184 185 186
   */
  function createField() {
    // Create a test field.
187
    $this->fieldUIAddNewField('admin/structure/types/manage/' . $this->contentType, $this->fieldNameInput, $this->fieldLabel);
188 189 190 191 192 193
  }

  /**
   * Tests editing an existing field.
   */
  function updateField() {
194
    $field_id = 'node.' . $this->contentType . '.' . $this->fieldName;
195
    // Go to the field edit page.
196
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields/' . $field_id . '/storage');
197
    $this->assertEscaped($this->fieldLabel);
198 199 200 201

    // Populate the field settings with new settings.
    $string = 'updated dummy test string';
    $edit = array(
202
      'settings[test_field_storage_setting]' => $string,
203
    );
204
    $this->drupalPostForm(NULL, $edit, t('Save field settings'));
205

206
    // Go to the field edit page.
207
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields/' . $field_id);
208
    $edit = array(
209
      'settings[test_field_setting]' => $string,
210
    );
211
    $this->assertText(t('Default value'), 'Default value heading is shown');
212
    $this->drupalPostForm(NULL, $edit, t('Save settings'));
213 214

    // Assert the field settings are correct.
215
    $this->assertFieldSettings($this->contentType, $this->fieldName, $string);
216 217

    // Assert redirection back to the "manage fields" page.
218
    $this->assertUrl('admin/structure/types/manage/' . $this->contentType . '/fields');
219 220 221 222 223 224
  }

  /**
   * Tests adding an existing field in another content type.
   */
  function addExistingField() {
225
    // Check "Re-use existing field" appears.
226 227
    $this->drupalGet('admin/structure/types/manage/page/fields/add-field');
    $this->assertRaw(t('Re-use an existing field'), '"Re-use existing field" was found.');
228

229 230
    // Check that fields of other entity types (here, the 'comment_body' field)
    // do not show up in the "Re-use existing field" list.
231 232
    $this->assertFalse($this->xpath('//select[@id="edit-existing-storage-name"]//option[@value="comment"]'), 'The list of options respects entity type restrictions.');
    // Validate the FALSE assertion above by also testing a valid one.
233
    $this->assertTrue($this->xpath('//select[@id="edit-existing-storage-name"]//option[@value=:field_name]', array(':field_name' => $this->fieldName)), 'The list of options shows a valid option.');
234 235

    // Add a new field based on an existing field.
236
    $this->fieldUIAddExistingField("admin/structure/types/manage/page", $this->fieldName, $this->fieldLabel . '_2');
237 238
  }

239 240 241 242 243 244 245
  /**
   * Tests the cardinality settings of a field.
   *
   * We do not test if the number can be submitted with anything else than a
   * numeric value. That is tested already in FormTest::testNumber().
   */
  function cardinalitySettings() {
246
    $field_edit_path = 'admin/structure/types/manage/article/fields/node.article.body/storage';
247 248

    // Assert the cardinality other field cannot be empty when cardinality is
249
    // set to 'number'.
250
    $edit = array(
251 252
      'cardinality' => 'number',
      'cardinality_number' => '',
253
    );
254
    $this->drupalPostForm($field_edit_path, $edit, t('Save field settings'));
255 256
    $this->assertText('Number of values is required.');

257
    // Submit a custom number.
258
    $edit = array(
259 260
      'cardinality' => 'number',
      'cardinality_number' => 6,
261
    );
262
    $this->drupalPostForm($field_edit_path, $edit, t('Save field settings'));
263
    $this->assertText('Updated field Body field settings.');
264
    $this->drupalGet($field_edit_path);
265 266
    $this->assertFieldByXPath("//select[@name='cardinality']", 'number');
    $this->assertFieldByXPath("//input[@name='cardinality_number']", 6);
267

268 269 270 271 272 273
    // Check that tabs displayed.
    $this->assertLink(t('Edit'));
    $this->assertLinkByHref('admin/structure/types/manage/article/fields/node.article.body');
    $this->assertLink(t('Field settings'));
    $this->assertLinkByHref($field_edit_path);

274
    // Set to unlimited.
275
    $edit = array(
276
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
277
    );
278
    $this->drupalPostForm($field_edit_path, $edit, t('Save field settings'));
279
    $this->assertText('Updated field Body field settings.');
280
    $this->drupalGet($field_edit_path);
281 282
    $this->assertFieldByXPath("//select[@name='cardinality']", FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $this->assertFieldByXPath("//input[@name='cardinality_number']", 1);
283 284
  }

285
  /**
286
   * Tests deleting a field from the field edit form.
287
   */
288 289
  protected function deleteField() {
    // Delete the field.
290 291
    $field_id = 'node.' . $this->contentType . '.' . $this->fieldName;
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields/' . $field_id);
292
    $this->clickLink(t('Delete'));
293 294 295
    $this->assertResponse(200);
  }

296 297 298 299
  /**
   * Tests that persistent field storage appears in the field UI.
   */
  protected function addPersistentFieldStorage() {
300
    $field_storage = FieldStorageConfig::loadByName('node', $this->fieldName);
301 302 303 304 305
    // Persist the field storage even if there are no fields.
    $field_storage->set('persist_with_no_fields', TRUE)->save();
    // Delete all instances of the field.
    foreach ($field_storage->getBundles() as $node_type) {
      // Delete all the body field instances.
306 307
      $this->drupalGet('admin/structure/types/manage/' . $node_type . '/fields/node.' . $node_type . '.' . $this->fieldName);
      $this->clickLink(t('Delete'));
308 309 310
      $this->drupalPostForm(NULL, array(), t('Delete'));
    }
    // Check "Re-use existing field" appears.
311 312
    $this->drupalGet('admin/structure/types/manage/page/fields/add-field');
    $this->assertRaw(t('Re-use an existing field'), '"Re-use existing field" was found.');
313 314 315

    // Ensure that we test with a label that contains HTML.
    $label = $this->randomString(4) . '<br/>' . $this->randomString(4);
316
    // Add a new field for the orphaned storage.
317
    $this->fieldUIAddExistingField("admin/structure/types/manage/page", $this->fieldName, $label);
318 319
  }

320 321 322 323
  /**
   * Asserts field settings are as expected.
   *
   * @param $bundle
324
   *   The bundle name for the field.
325
   * @param $field_name
326
   *   The field name for the field.
327 328 329
   * @param $string
   *   The settings text.
   * @param $entity_type
330
   *   The entity type for the field.
331 332
   */
  function assertFieldSettings($bundle, $field_name, $string = 'dummy test string', $entity_type = 'node') {
333 334 335
    // Assert field storage settings.
    $field_storage = FieldStorageConfig::loadByName($entity_type, $field_name);
    $this->assertTrue($field_storage->getSetting('test_field_storage_setting') == $string, 'Field storage settings were found.');
336

337 338 339
    // Assert field settings.
    $field = FieldConfig::loadByName($entity_type, $bundle, $field_name);
    $this->assertTrue($field->getSetting('test_field_setting') == $string, 'Field settings were found.');
340 341
  }

342 343 344 345 346
  /**
   * Tests that the 'field_prefix' setting works on Field UI.
   */
  function testFieldPrefix() {
    // Change default field prefix.
347
    $field_prefix = strtolower($this->randomMachineName(10));
348
    $this->config('field_ui.settings')->set('field_prefix', $field_prefix)->save();
349 350 351

    // Create a field input and label exceeding the new maxlength, which is 22.
    $field_exceed_max_length_label = $this->randomString(23);
352
    $field_exceed_max_length_input = $this->randomMachineName(23);
353 354 355

    // Try to create the field.
    $edit = array(
356 357
      'label' => $field_exceed_max_length_label,
      'field_name' => $field_exceed_max_length_input,
358
    );
359
    $this->drupalPostForm('admin/structure/types/manage/' . $this->contentType . '/fields/add-field', $edit, t('Save and continue'));
360
    $this->assertText('Machine-readable name cannot be longer than 22 characters but is currently 23 characters long.');
361 362

    // Create a valid field.
363 364 365
    $this->fieldUIAddNewField('admin/structure/types/manage/' . $this->contentType, $this->fieldNameInput, $this->fieldLabel);
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields/node.' . $this->contentType . '.' . $field_prefix . $this->fieldNameInput);
    $this->assertText(format_string('@label settings for @type', array('@label' => $this->fieldLabel, '@type' => $this->contentType)));
366 367
  }

368 369 370 371
  /**
   * Tests that default value is correctly validated and saved.
   */
  function testDefaultValue() {
372
    // Create a test field storage and field.
373
    $field_name = 'test';
374
    FieldStorageConfig::create(array(
375
      'field_name' => $field_name,
376
      'entity_type' => 'node',
377
      'type' => 'test_field'
378
    ))->save();
379
    $field = FieldConfig::create(array(
380 381
      'field_name' => $field_name,
      'entity_type' => 'node',
382
      'bundle' => $this->contentType,
383
    ));
384
    $field->save();
385

386
    entity_get_form_display('node', $this->contentType, 'default')
387 388 389
      ->setComponent($field_name)
      ->save();

390
    $admin_path = 'admin/structure/types/manage/' . $this->contentType . '/fields/' . $field->id();
391 392
    $element_id = "edit-default-value-input-$field_name-0-value";
    $element_name = "default_value_input[{$field_name}][0][value]";
393
    $this->drupalGet($admin_path);
394
    $this->assertFieldById($element_id, '', 'The default value widget was empty.');
395 396 397

    // Check that invalid default values are rejected.
    $edit = array($element_name => '-1');
398
    $this->drupalPostForm($admin_path, $edit, t('Save settings'));
399
    $this->assertText("$field_name does not accept the value -1", 'Form validation failed.');
400 401 402

    // Check that the default value is saved.
    $edit = array($element_name => '1');
403
    $this->drupalPostForm($admin_path, $edit, t('Save settings'));
404
    $this->assertText("Saved $field_name configuration", 'The form was successfully submitted.');
405
    $field = FieldConfig::loadByName('node', $this->contentType, $field_name);
406
    $this->assertEqual($field->getDefaultValueLiteral(), array(array('value' => 1)), 'The default value was correctly saved.');
407 408 409

    // Check that the default value shows up in the form
    $this->drupalGet($admin_path);
410
    $this->assertFieldById($element_id, '1', 'The default value widget was displayed with the correct value.');
411 412 413

    // Check that the default value can be emptied.
    $edit = array($element_name => '');
414
    $this->drupalPostForm(NULL, $edit, t('Save settings'));
415
    $this->assertText("Saved $field_name configuration", 'The form was successfully submitted.');
416
    $field = FieldConfig::loadByName('node', $this->contentType, $field_name);
417
    $this->assertEqual($field->getDefaultValueLiteral(), NULL, 'The default value was correctly saved.');
418

419 420 421
    // Check that the default value can be empty when the field is marked as
    // required and can store unlimited values.
    $field_storage = FieldStorageConfig::loadByName('node', $field_name);
422
    $field_storage->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
423 424 425 426
    $field_storage->save();

    $this->drupalGet($admin_path);
    $edit = array(
427
      'required' => 1,
428 429 430 431 432 433
    );
    $this->drupalPostForm(NULL, $edit, t('Save settings'));

    $this->drupalGet($admin_path);
    $this->drupalPostForm(NULL, array(), t('Save settings'));
    $this->assertText("Saved $field_name configuration", 'The form was successfully submitted.');
434
    $field = FieldConfig::loadByName('node', $this->contentType, $field_name);
435
    $this->assertEqual($field->getDefaultValueLiteral(), NULL, 'The default value was correctly saved.');
436

437
    // Check that the default widget is used when the field is hidden.
438
    entity_get_form_display($field->getTargetEntityTypeId(), $field->getTargetBundle(), 'default')
439
      ->removeComponent($field_name)->save();
440
    $this->drupalGet($admin_path);
441
    $this->assertFieldById($element_id, '', 'The default value widget was displayed when field is hidden.');
442 443 444
  }

  /**
445
   * Tests that deletion removes field storages and fields as expected.
446 447 448
   */
  function testDeleteField() {
    // Create a new field.
449 450
    $bundle_path1 = 'admin/structure/types/manage/' . $this->contentType;
    $this->fieldUIAddNewField($bundle_path1, $this->fieldNameInput, $this->fieldLabel);
451 452

    // Create an additional node type.
453
    $type_name2 = strtolower($this->randomMachineName(8)) . '_test';
454
    $type2 = $this->drupalCreateContentType(array('name' => $type_name2, 'type' => $type_name2));
455
    $type_name2 = $type2->id();
456

457
    // Add a field to the second node type.
458
    $bundle_path2 = 'admin/structure/types/manage/' . $type_name2;
459
    $this->fieldUIAddExistingField($bundle_path2, $this->fieldName, $this->fieldLabel);
460

461
    // Delete the first field.
462
    $this->fieldUIDeleteField($bundle_path1, "node.$this->contentType.$this->fieldName", $this->fieldLabel, $this->contentType);
463

464
    // Check that the field was deleted.
465
    $this->assertNull(FieldConfig::loadByName('node', $this->contentType, $this->fieldName), 'Field was deleted.');
466
    // Check that the field storage was not deleted
467
    $this->assertNotNull(FieldStorageConfig::loadByName('node', $this->fieldName), 'Field storage was not deleted.');
468

469
    // Delete the second field.
470
    $this->fieldUIDeleteField($bundle_path2, "node.$type_name2.$this->fieldName", $this->fieldLabel, $type_name2);
471

472
    // Check that the field was deleted.
473
    $this->assertNull(FieldConfig::loadByName('node', $type_name2, $this->fieldName), 'Field was deleted.');
474
    // Check that the field storage was deleted too.
475
    $this->assertNull(FieldStorageConfig::loadByName('node', $this->fieldName), 'Field storage was deleted.');
476 477
  }

478 479 480 481 482
  /**
   * Tests that Field UI respects disallowed field names.
   */
  function testDisallowedFieldNames() {
    // Reset the field prefix so we can test properly.
483
    $this->config('field_ui.settings')->set('field_prefix', '')->save();
484 485 486

    $label = 'Disallowed field';
    $edit = array(
487 488
      'label' => $label,
      'new_storage_type' => 'test_field',
489 490 491
    );

    // Try with an entity key.
492
    $edit['field_name'] = 'title';
493
    $bundle_path = 'admin/structure/types/manage/' . $this->contentType;
494
    $this->drupalPostForm("$bundle_path/fields/add-field",  $edit, t('Save and continue'));
495
    $this->assertText(t('The machine-readable name is already in use. It must be unique.'));
496 497

    // Try with a base field.
498
    $edit['field_name'] = 'sticky';
499
    $bundle_path = 'admin/structure/types/manage/' . $this->contentType;
500
    $this->drupalPostForm("$bundle_path/fields/add-field",  $edit, t('Save and continue'));
501
    $this->assertText(t('The machine-readable name is already in use. It must be unique.'));
502 503
  }

504 505 506 507 508
  /**
   * Tests that Field UI respects locked fields.
   */
  function testLockedField() {
    // Create a locked field and attach it to a bundle. We need to do this
509
    // programmatically as there's no way to create a locked field through UI.
510
    $field_name = strtolower($this->randomMachineName(8));
511
    $field_storage = FieldStorageConfig::create(array(
512
      'field_name' => $field_name,
513
      'entity_type' => 'node',
514 515 516 517
      'type' => 'test_field',
      'cardinality' => 1,
      'locked' => TRUE
    ));
518
    $field_storage->save();
519
    FieldConfig::create(array(
520
      'field_storage' => $field_storage,
521
      'bundle' => $this->contentType,
522
    ))->save();
523
    entity_get_form_display('node', $this->contentType, 'default')
524
      ->setComponent($field_name, array(
525 526 527
        'type' => 'test_field_widget',
      ))
      ->save();
528 529

    // Check that the links for edit and delete are not present.
530
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields');
531
    $locked = $this->xpath('//tr[@id=:field_name]/td[4]', array(':field_name' => $field_name));
532
    $this->assertTrue(in_array('Locked', $locked), 'Field is marked as Locked in the UI');
533
    $edit_link = $this->xpath('//tr[@id=:field_name]/td[4]', array(':field_name' => $field_name));
534
    $this->assertFalse(in_array('edit', $edit_link), 'Edit option for locked field is not present the UI');
535
    $delete_link = $this->xpath('//tr[@id=:field_name]/td[4]', array(':field_name' => $field_name));
536
    $this->assertFalse(in_array('delete', $delete_link), 'Delete option for locked field is not present the UI');
537
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields/node.' . $this->contentType . '.' . $field_name . '/delete');
538
    $this->assertResponse(403);
539 540
  }

541
  /**
542
   * Tests that Field UI respects the 'no_ui' flag in the field type definition.
543 544 545
   */
  function testHiddenFields() {
    // Check that the field type is not available in the 'add new field' row.
546
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields/add-field');
547 548
    $this->assertFalse($this->xpath('//select[@id="edit-new-storage-type"]//option[@value="hidden_test_field"]'), "The 'add new field' select respects field types 'no_ui' property.");
    $this->assertTrue($this->xpath('//select[@id="edit-new-storage-type"]//option[@value="shape"]'), "The 'add new field' select shows a valid option.");
549

550
    // Create a field storage and a field programmatically.
551
    $field_name = 'hidden_test_field';
552
    FieldStorageConfig::create(array(
553
      'field_name' => $field_name,
554 555 556
      'entity_type' => 'node',
      'type' => $field_name,
    ))->save();
557
    $field = array(
558
      'field_name' => $field_name,
559
      'bundle' => $this->contentType,
560 561 562
      'entity_type' => 'node',
      'label' => t('Hidden field'),
    );
563
    FieldConfig::create($field)->save();
564
    entity_get_form_display('node', $this->contentType, 'default')
565 566
      ->setComponent($field_name)
      ->save();
567
    $this->assertTrue(FieldConfig::load('node.' . $this->contentType . '.' . $field_name), format_string('A field of the field storage %field was created programmatically.', array('%field' => $field_name)));
568

569
    // Check that the newly added field appears on the 'Manage Fields'
570
    // screen.
571
    $this->drupalGet('admin/structure/types/manage/' . $this->contentType . '/fields');
572
    $this->assertFieldByXPath('//table[@id="field-overview"]//tr[@id="hidden-test-field"]//td[1]', $field['label'], 'Field was created and appears in the overview page.');
573

574
    // Check that the field does not appear in the 're-use existing field' row
575
    // on other bundles.
576 577 578
    $this->drupalGet('admin/structure/types/manage/page/fields/add-field');
    $this->assertFalse($this->xpath('//select[@id="edit-existing-storage-name"]//option[@value=:field_name]', array(':field_name' => $field_name)), "The 're-use existing field' select respects field types 'no_ui' property.");
    $this->assertTrue($this->xpath('//select[@id="edit-existing-storage-name"]//option[@value=:field_name]', array(':field_name' => 'field_tags')), "The 're-use existing field' select shows a valid option.");
579 580

    // Check that non-configurable fields are not available.
581
    $field_types = \Drupal::service('plugin.manager.field.field_type')->getDefinitions();
582
    foreach ($field_types as $field_type => $definition) {
583
      if (empty($definition['no_ui'])) {
584
        $this->assertTrue($this->xpath('//select[@id="edit-new-storage-type"]//option[@value=:field_type]', array(':field_type' => $field_type)), SafeMarkup::format('Configurable field type @field_type is available.', array('@field_type' => $field_type)));
585 586
      }
      else {
587
        $this->assertFalse($this->xpath('//select[@id="edit-new-storage-type"]//option[@value=:field_type]', array(':field_type' => $field_type)), SafeMarkup::format('Non-configurable field type @field_type is not available.', array('@field_type' => $field_type)));
588 589
      }
    }
590 591 592 593 594 595
  }

  /**
   * Tests renaming a bundle.
   */
  function testRenameBundle() {
596
    $type2 = strtolower($this->randomMachineName(8)) . '_test';
597 598 599 600

    $options = array(
      'type' => $type2,
    );
601
    $this->drupalPostForm('admin/structure/types/manage/' . $this->contentType, $options, t('Save content type'));
602
    $this->manageFieldsPage($type2);
603 604 605 606 607 608 609 610 611
  }

  /**
   * Tests that a duplicate field name is caught by validation.
   */
  function testDuplicateFieldName() {
    // field_tags already exists, so we're expecting an error when trying to
    // create a new field with the same name.
    $edit = array(
612 613
      'field_name' => 'tags',
      'label' => $this->randomMachineName(),
614
      'new_storage_type' => 'entity_reference',
615
    );
616
    $url = 'admin/structure/types/manage/' . $this->contentType . '/fields/add-field';
617
    $this->drupalPostForm($url, $edit, t('Save and continue'));
618 619 620 621

    $this->assertText(t('The machine-readable name is already in use. It must be unique.'));
    $this->assertUrl($url, array(), 'Stayed on the same page.');
  }
622

623 624 625 626 627 628 629 630 631 632 633
  /**
   * Tests that external URLs in the 'destinations' query parameter are blocked.
   */
  public function testExternalDestinations() {
    $options = [
      'query' => ['destinations' => ['http://example.com']],
    ];
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.body/storage', [], 'Save field settings', $options);
    // The external redirect should not fire.
    $this->assertUrl('admin/structure/types/manage/article/fields/node.article.body/storage', $options);
    $this->assertResponse(200);
634
    $this->assertRaw('Attempt to update field <em class="placeholder">Body</em> failed: <em class="placeholder">The internal path component &#039;http://example.com&#039; is external. You are not allowed to specify an external URL together with internal:/.</em>.');
635 636
  }

637
  /**
638
   * Tests that deletion removes field storages and fields as expected for a term.
639 640 641
   */
  function testDeleteTaxonomyField() {
    // Create a new field.
642
    $bundle_path = 'admin/structure/taxonomy/manage/tags/overview';
643

644
    $this->fieldUIAddNewField($bundle_path, $this->fieldNameInput, $this->fieldLabel);
645 646

    // Delete the field.
647
    $this->fieldUIDeleteField($bundle_path, "taxonomy_term.tags.$this->fieldName", $this->fieldLabel, 'Tags');
648

649
    // Check that the field was deleted.
650
    $this->assertNull(FieldConfig::loadByName('taxonomy_term', 'tags', $this->fieldName), 'Field was deleted.');
651
    // Check that the field storage was deleted too.
652
    $this->assertNull(FieldStorageConfig::loadByName('taxonomy_term', $this->fieldName), 'Field storage was deleted.');
653 654
  }

655 656 657 658 659
  /**
   * Tests that help descriptions render valid HTML.
   */
  function testHelpDescriptions() {
    // Create an image field
660
    FieldStorageConfig::create(array(
661
      'field_name' => 'field_image',
662
      'entity_type' => 'node',
663 664 665
      'type' => 'image',
    ))->save();

666
    FieldConfig::create(array(
667 668 669 670 671 672 673 674 675
      'field_name' => 'field_image',
      'entity_type' => 'node',
      'label' => 'Image',
      'bundle' => 'article',
    ))->save();

    entity_get_form_display('node', 'article', 'default')->setComponent('field_image')->save();

    $edit = array(
676
      'description' => '<strong>Test with an upload field.',
677
    );
678
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.field_image', $edit, t('Save settings'));
679

680 681 682 683 684
    // Check that hook_field_widget_form_alter() does believe this is the
    // default value form.
    $this->drupalGet('admin/structure/types/manage/article/fields/node.article.field_tags');
    $this->assertText('From hook_field_widget_form_alter(): Default form is true.', 'Default value form in hook_field_widget_form_alter().');

685
    $edit = array(
686
      'description' => '<em>Test with a non upload field.',
687
    );
688
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.field_tags', $edit, t('Save settings'));
689 690 691 692 693

    $this->drupalGet('node/add/article');
    $this->assertRaw('<strong>Test with an upload field.</strong>');
    $this->assertRaw('<em>Test with a non upload field.</em>');
  }
694 695 696 697 698 699

  /**
   * Tests that the field list administration page operates correctly.
   */
  function fieldListAdminPage() {
    $this->drupalGet('admin/reports/fields');
700 701
    $this->assertText($this->fieldName, 'Field name is displayed in field list.');
    $this->assertTrue($this->assertLinkByHref('admin/structure/types/manage/' . $this->contentType . '/fields'), 'Link to content type using field is displayed in field list.');
702
  }
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

  /**
   * Tests the "preconfigured field" functionality.
   *
   * @see \Drupal\Core\Field\PreconfiguredFieldUiOptionsInterface
   */
  public function testPreconfiguredFields() {
    $this->drupalGet('admin/structure/types/manage/article/fields/add-field');

    // Check that the preconfigured field option exist alongside the regular
    // field type option.
    $this->assertOption('edit-new-storage-type', 'field_ui:test_field_with_preconfigured_options:custom_options');
    $this->assertOption('edit-new-storage-type', 'test_field_with_preconfigured_options');

    // Add a field with every possible preconfigured value.
    $this->fieldUIAddNewField(NULL, 'test_custom_options', 'Test label', 'field_ui:test_field_with_preconfigured_options:custom_options');
    $field_storage = FieldStorageConfig::loadByName('node', 'field_test_custom_options');
    $this->assertEqual($field_storage->getCardinality(), FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $this->assertEqual($field_storage->getSetting('test_field_storage_setting'), 'preconfigured_storage_setting');

    $field = FieldConfig::loadByName('node', 'article', 'field_test_custom_options');
    $this->assertTrue($field->isRequired());
    $this->assertEqual($field->getSetting('test_field_setting'), 'preconfigured_field_setting');

    $form_display = entity_get_form_display('node', 'article', 'default');
    $this->assertEqual($form_display->getComponent('field_test_custom_options')['type'], 'test_field_widget_multiple');
    $view_display = entity_get_display('node', 'article', 'default');
    $this->assertEqual($view_display->getComponent('field_test_custom_options')['type'], 'field_test_multiple');
  }

733
}