You are here

public function BooleanFieldTest::testFormAccess in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/field/tests/src/Functional/Boolean/BooleanFieldTest.php \Drupal\Tests\field\Functional\Boolean\BooleanFieldTest::testFormAccess()

Test field access.

File

core/modules/field/tests/src/Functional/Boolean/BooleanFieldTest.php, line 191

Class

BooleanFieldTest
Tests boolean field functionality.

Namespace

Drupal\Tests\field\Functional\Boolean

Code

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();

  /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
  $display_repository = \Drupal::service('entity_display.repository');

  // Create a form display for the default form mode.
  $display_repository
    ->getFormDisplay('entity_test', 'entity_test')
    ->setComponent($field_name, [
    'type' => 'boolean_checkbox',
  ])
    ->save();

  // Create a display for the full view mode.
  $display_repository
    ->getViewDisplay('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
    ->getUrl(), $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
    ->getUrl(), $match);
  $id = $match[1];
  $this
    ->assertText(t('entity_test @id has been created.', [
    '@id' => $id,
  ]));
}