You are here

public function FormTest::testFieldFormSingleRequired in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/field/tests/src/Functional/FormTest.php \Drupal\Tests\field\Functional\FormTest::testFieldFormSingleRequired()
  2. 9 core/modules/field/tests/src/Functional/FormTest.php \Drupal\Tests\field\Functional\FormTest::testFieldFormSingleRequired()

File

core/modules/field/tests/src/Functional/FormTest.php, line 220

Class

FormTest
Tests field form handling.

Namespace

Drupal\Tests\field\Functional

Code

public function testFieldFormSingleRequired() {
  $field_storage = $this->fieldStorageSingle;
  $field_name = $field_storage['field_name'];
  $this->field['field_name'] = $field_name;
  $this->field['required'] = TRUE;
  FieldStorageConfig::create($field_storage)
    ->save();
  FieldConfig::create($this->field)
    ->save();
  \Drupal::service('entity_display.repository')
    ->getFormDisplay($this->field['entity_type'], $this->field['bundle'])
    ->setComponent($field_name)
    ->save();

  // Submit with missing required value.
  $edit = [];
  $this
    ->drupalGet('entity_test/add');
  $this
    ->submitForm($edit, 'Save');
  $this
    ->assertSession()
    ->pageTextContains("{$this->field['label']} field is required.");

  // Create an entity
  $value = mt_rand(1, 127);
  $edit = [
    "{$field_name}[0][value]" => $value,
  ];
  $this
    ->submitForm($edit, 'Save');
  preg_match('|entity_test/manage/(\\d+)|', $this
    ->getUrl(), $match);
  $id = $match[1];
  $this
    ->assertSession()
    ->pageTextContains('entity_test ' . $id . ' has been created.');
  $entity = EntityTest::load($id);
  $this
    ->assertEquals($value, $entity->{$field_name}->value, 'Field value was saved');

  // Edit with missing required value.
  $value = '';
  $edit = [
    "{$field_name}[0][value]" => $value,
  ];
  $this
    ->drupalGet('entity_test/manage/' . $id . '/edit');
  $this
    ->submitForm($edit, 'Save');
  $this
    ->assertSession()
    ->pageTextContains("{$this->field['label']} field is required.");
}