You are here

public function OptionsWidgetsTest::testRadioButtons in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/options/tests/src/Functional/OptionsWidgetsTest.php \Drupal\Tests\options\Functional\OptionsWidgetsTest::testRadioButtons()

Tests the 'options_buttons' widget (single select).

File

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

Class

OptionsWidgetsTest
Tests the Options widgets.

Namespace

Drupal\Tests\options\Functional

Code

public function testRadioButtons() {

  // Create an instance of the 'single value' field.
  $field = FieldConfig::create([
    'field_storage' => $this->card1,
    'bundle' => 'entity_test',
  ]);
  $field
    ->save();
  \Drupal::service('entity_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();
  $entity_init = clone $entity;

  // With no field data, no buttons are checked.
  $this
    ->drupalGet('entity_test/manage/' . $entity
    ->id() . '/edit');
  $this
    ->assertNoFieldChecked('edit-card-1-0');
  $this
    ->assertNoFieldChecked('edit-card-1-1');
  $this
    ->assertNoFieldChecked('edit-card-1-2');
  $this
    ->assertRaw('Some dangerous &amp; unescaped <strong>markup</strong>', 'Option text was properly filtered.');
  $this
    ->assertRaw('Some HTML encoded markup with &lt; &amp; &gt;');

  // Select first option.
  $edit = [
    'card_1' => 0,
  ];
  $this
    ->drupalPostForm(NULL, $edit, t('Save'));
  $this
    ->assertFieldValues($entity_init, 'card_1', [
    0,
  ]);

  // Check that the selected button is checked.
  $this
    ->drupalGet('entity_test/manage/' . $entity
    ->id() . '/edit');
  $this
    ->assertFieldChecked('edit-card-1-0');
  $this
    ->assertNoFieldChecked('edit-card-1-1');
  $this
    ->assertNoFieldChecked('edit-card-1-2');

  // Unselect option.
  $edit = [
    'card_1' => '_none',
  ];
  $this
    ->drupalPostForm(NULL, $edit, t('Save'));
  $this
    ->assertFieldValues($entity_init, 'card_1', []);

  // Check that required radios with one option is auto-selected.
  $this->card1
    ->setSetting('allowed_values', [
    99 => 'Only allowed value',
  ]);
  $this->card1
    ->save();
  $field
    ->setRequired(TRUE);
  $field
    ->save();
  $this
    ->drupalGet('entity_test/manage/' . $entity
    ->id() . '/edit');
  $this
    ->assertFieldChecked('edit-card-1-99');
}