You are here

public function ElementsTest::testValueCallback in Select (or other) 8

Same name and namespace in other branches
  1. 8.3 Tests/src/Unit/ElementsTest.php \Drupal\Tests\select_or_other\Unit\ElementsTest::testValueCallback()
  2. 4.x tests/src/Unit/ElementsTest.php \Drupal\Tests\select_or_other\Unit\ElementsTest::testValueCallback()

Tests the value callback.

File

tests/src/Unit/ElementsTest.php, line 36

Class

ElementsTest
Tests the form element implementation.

Namespace

Drupal\Tests\select_or_other\Unit

Code

public function testValueCallback() {
  $form_state = new FormState();
  $element = [
    '#multiple' => FALSE,
  ];
  $input = [
    'select' => 'Selected text',
    'other' => 'Other text',
  ];
  $expected = [
    $input['select'],
  ];
  $values = ElementBase::valueCallback($element, $input, $form_state);
  $this
    ->assertArrayEquals($expected, $values, 'Returned single value select.');
  $input['select'] = 'select_or_other';
  $expected = [
    $input['other'],
  ];
  $values = ElementBase::valueCallback($element, $input, $form_state);
  $this
    ->assertArrayEquals($expected, $values, 'Returned single value other.');
  $element['#multiple'] = TRUE;
  $input['select'] = [
    'Selected text',
  ];
  $expected = [
    'select' => $input['select'],
    'other' => [],
  ];
  $values = ElementBase::valueCallback($element, $input, $form_state);
  $this
    ->assertArrayEquals($expected, $values, 'Returned select array and empty other array.');
  $input['select'][] = 'select_or_other';
  $expected['other'] = [
    $input['other'],
  ];
  $values = ElementBase::valueCallback($element, $input, $form_state);
  $this
    ->assertArrayEquals($expected, $values, 'Returned select array and other array.');
  $input['select'] = [
    'select_or_other',
  ];
  $expected = [
    'select' => [],
    'other' => [
      $input['other'],
    ],
  ];
  $values = ElementBase::valueCallback($element, $input, $form_state);
  $this
    ->assertArrayEquals($expected, $values, 'Returned empty select and other array.');
  $input['select'][] = 'Selected';
  $element['#merged_values'] = TRUE;
  $expected = [
    'Selected',
    $input['other'],
  ];
  $values = ElementBase::valueCallback($element, $input, $form_state);
  $this
    ->assertArrayEquals($expected, $values, 'Returned merged array.');
  $input['select'] = [
    'Selected',
  ];
  $input['other'] = '';
  $expected = [
    'Selected',
  ];
  $values = ElementBase::valueCallback($element, $input, $form_state);
  $this
    ->assertArrayEquals($expected, $values, 'Returned merged array.');
  foreach ([
    TRUE,
    FALSE,
  ] as $multiple) {
    $element['#multiple'] = $multiple;
    $input = [
      'other' => 'Other value',
    ];
    $expected = [];
    $values = ElementBase::valueCallback($element, $input, $form_state);
    $this
      ->assertArrayEquals($expected, $values, 'Submitting only the other value results in an empty array.');
  }
}