function FormTest::testFieldFormDefaultValue

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

Tests field widget default values on entity forms.

File

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

Class

FormTest
Tests field form handling.

Namespace

Drupal\Tests\field\Functional

Code

public function testFieldFormDefaultValue() : void {
    $field_storage = $this->fieldStorageSingle;
    $field_name = $field_storage['field_name'];
    $this->field['field_name'] = $field_name;
    $default = rand(1, 127);
    $this->field['default_value'] = [
        [
            'value' => $default,
        ],
    ];
    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();
    // Display creation form.
    $this->drupalGet('entity_test/add');
    // Test that the default value is displayed correctly.
    $this->assertSession()
        ->fieldValueEquals("{$field_name}[0][value]", $default);
    // Try to submit an empty value.
    $edit = [
        "{$field_name}[0][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->assertTrue($entity->{$field_name}
        ->isEmpty(), 'Field is now empty.');
}

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