function OptionsWidgetsTest::testEmptyValue

Same name and namespace in other branches
  1. 9 core/modules/options/tests/src/Functional/OptionsWidgetsTest.php \Drupal\Tests\options\Functional\OptionsWidgetsTest::testEmptyValue()
  2. 8.9.x 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 591

Class

OptionsWidgetsTest
Tests the Options widgets.

Namespace

Drupal\Tests\options\Functional

Code

public function testEmptyValue() : void {
  // 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');
  // Verify that a test radio button has a "None" choice.
  $this->assertSession()
    ->elementExists('xpath', '//div[@id="edit-card-1"]//input[@value="_none"]');
  // Verify that a test radio button has a "N/A" choice..
  $this->assertSession()
    ->elementExists('xpath', '//div[@id="edit-card-1"]//label[@for="edit-card-1-none"]');
  $this->assertSession()
    ->elementTextEquals('xpath', '//div[@id="edit-card-1"]//label[@for="edit-card-1-none"]', "N/A");
  // 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.
  $option = $this->assertSession()
    ->optionExists('edit-card-1', '_none');
  $this->assertSame('- None -', $option->getText());
}

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