function OptionsWidgetsTest::testEmptyValue

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

Tests the 'options_select' and 'options_button' widget for empty value.

File

core/modules/options/tests/src/Functional/OptionsWidgetsTest.php, line 542

Class

OptionsWidgetsTest
Tests the Options widgets.

Namespace

Drupal\Tests\options\Functional

Code

public function testEmptyValue() {
    // Create an instance of the 'single value' field.
    $field = FieldConfig::create([
        'field_storage' => $this->card1,
        'bundle' => 'entity_test',
    ]);
    $field->save();
    
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    // Change it to the check boxes/radio buttons widget.
    $display_repository->getFormDisplay('entity_test', 'entity_test')
        ->setComponent($this->card1
        ->getName(), [
        'type' => 'options_buttons',
    ])
        ->save();
    // Create an entity.
    $entity = EntityTest::create([
        'user_id' => 1,
        'name' => $this->randomMachineName(),
    ]);
    $entity->save();
    // Display form: check that _none options are present and has label.
    $this->drupalGet('entity_test/manage/' . $entity->id() . '/edit');
    $this->assertNotEmpty($this->xpath('//div[@id=:id]//input[@value=:value]', [
        ':id' => 'edit-card-1',
        ':value' => '_none',
    ]), 'A test radio button has a "None" choice.');
    $this->assertNotEmpty($this->xpath('//div[@id=:id]//label[@for=:for and text()=:label]', [
        ':id' => 'edit-card-1',
        ':for' => 'edit-card-1-none',
        ':label' => 'N/A',
    ]), 'A test radio button has a "N/A" choice.');
    // Change it to the select widget.
    $display_repository->getFormDisplay('entity_test', 'entity_test')
        ->setComponent($this->card1
        ->getName(), [
        'type' => 'options_select',
    ])
        ->save();
    // Display form: check that _none options are present and has label.
    $this->drupalGet('entity_test/manage/' . $entity->id() . '/edit');
    // A required field without any value has a "none" option.
    $this->assertNotEmpty($this->xpath('//select[@id=:id]//option[@value="_none" and text()=:label]', [
        ':id' => 'edit-card-1',
        ':label' => '- None -',
    ]), 'A test select has a "None" choice.');
}

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