function FormTest::testFieldFormSingleRequired

Same name in other branches
  1. 9 core/modules/field/tests/src/Functional/FormTest.php \Drupal\Tests\field\Functional\FormTest::testFieldFormSingleRequired()
  2. 10 core/modules/field/tests/src/Functional/FormTest.php \Drupal\Tests\field\Functional\FormTest::testFieldFormSingleRequired()
  3. 11.x core/modules/field/tests/src/Functional/FormTest.php \Drupal\Tests\field\Functional\FormTest::testFieldFormSingleRequired()

File

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

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->drupalPostForm('entity_test/add', $edit, t('Save'));
    $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 = [
        "{$field_name}[0][value]" => $value,
    ];
    $this->drupalPostForm(NULL, $edit, 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,
    ]), '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 = [
        "{$field_name}[0][value]" => $value,
    ];
    $this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save'));
    $this->assertRaw(t('@name field is required.', [
        '@name' => $this->field['label'],
    ]), 'Required field with no value fails validation');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.