diff --git a/core/lib/Drupal/Core/Form/FormStateInterface.php b/core/lib/Drupal/Core/Form/FormStateInterface.php index ebd2ec6..7706dc2 100644 --- a/core/lib/Drupal/Core/Form/FormStateInterface.php +++ b/core/lib/Drupal/Core/Form/FormStateInterface.php @@ -377,7 +377,23 @@ public function hasValue($key); public function isValueEmpty($key); /** - * @todo. + * Gets the form value that corresponds to a given form element. + * + * @param array $element + * The form element that should have its value retrieved; in most cases you + * can just pass in the element from the $form array, although the only + * component that is actually used is '#parents'. If constructing yourself, + * set $element['#parents'] to be an array giving the path through the form + * array's keys to the element whose value you want to retrieve. For + * instance, if you want to retrieve the value of $form['elem1']['elem2'], + * which should be stored in $form_state->getValue(['elem1', 'elem2']), you + * would set $element['#parents'] = ['elem1', 'elem2']. + * @param bool $exists + * (optional) If given, an already defined variable that is altered by + * reference. + * + * @return mixed + * The value for the form element, if it exists, NULL otherwise. */ public function getValueForElement(array $element, &$exists = NULL); diff --git a/core/tests/Drupal/Tests/Core/Form/FormStateTest.php b/core/tests/Drupal/Tests/Core/Form/FormStateTest.php index 24904e3..3e6cf48 100644 --- a/core/tests/Drupal/Tests/Core/Form/FormStateTest.php +++ b/core/tests/Drupal/Tests/Core/Form/FormStateTest.php @@ -143,6 +143,47 @@ public function testFormErrorsDuringSubmission() { } /** + * @covers ::getValueForElement + * + * @dataProvider providerTestGetValueForElement + */ + public function testGetValueForElement($set_data, $expected) { + $element = [ + '#parents' => [ + 'foo', + 'bar', + ], + ]; + $value = $this->randomMachineName(); + + $input_exists = NULL; + $form_state = new FormState(); + if ($set_data) { + $form_state->setValue(['foo', 'bar'], $value); + } + + $value_from_form_state = $form_state->getValueForElement($element, $input_exists); + if ($set_data) { + $this->assertSame($value, $value_from_form_state); + } + else { + $this->assertNull($value_from_form_state); + } + $this->assertSame($expected, $input_exists); + } + + public function providerTestGetValueForElement() { + $data = []; + $data[] = [ + FALSE, FALSE, + ]; + $data[] = [ + TRUE, TRUE, + ]; + return $data; + } + + /** * Tests that setting the value for an element adds to the values. * * @covers ::setValueForElement