diff --git a/src/Symfony/Component/DomCrawler/CHANGELOG.md b/src/Symfony/Component/DomCrawler/CHANGELOG.md index 53395956f3be9..d3b11196cdb8c 100644 --- a/src/Symfony/Component/DomCrawler/CHANGELOG.md +++ b/src/Symfony/Component/DomCrawler/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +7.1 +--- + + * Allow to add choices to single select + 7.0 --- diff --git a/src/Symfony/Component/DomCrawler/Field/ChoiceFormField.php b/src/Symfony/Component/DomCrawler/Field/ChoiceFormField.php index ac7ee8d2c6f36..04d4ecf06cac6 100644 --- a/src/Symfony/Component/DomCrawler/Field/ChoiceFormField.php +++ b/src/Symfony/Component/DomCrawler/Field/ChoiceFormField.php @@ -143,14 +143,14 @@ public function setValue(string|array|bool|null $value): void */ public function addChoice(\DOMElement $node): void { - if (!$this->multiple && 'radio' !== $this->type) { + if (!$this->multiple && ('radio' !== $this->type && 'select' !== $this->type)) { throw new \LogicException(sprintf('Unable to add a choice for "%s" as it is not multiple or is not a radio button.', $this->name)); } $option = $this->buildOptionValue($node); $this->options[] = $option; - if ($node->hasAttribute('checked')) { + if ($node->hasAttribute('checked') || $node->hasAttribute('selected')) { $this->value = $option['value']; } } diff --git a/src/Symfony/Component/DomCrawler/Tests/Field/ChoiceFormFieldTest.php b/src/Symfony/Component/DomCrawler/Tests/Field/ChoiceFormFieldTest.php index 176ea5927fe1c..6766888e0ca4d 100644 --- a/src/Symfony/Component/DomCrawler/Tests/Field/ChoiceFormFieldTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/Field/ChoiceFormFieldTest.php @@ -110,6 +110,18 @@ public function testSelects() } catch (\InvalidArgumentException $e) { $this->assertTrue(true, '->setValue() throws an \InvalidArgumentException if the value is an array'); } + + $option = $this->createNode('option', 'Hello World', ['value' => 'hello_world']); + $field->addChoice($option); + + $this->assertNotSame('hello_world', $field->getValue()); + $field->setValue('hello_world'); + $this->assertSame('hello_world', $field->getValue(), '->setValue() changes the selected option to dynamically added one'); + + $option = $this->createNode('option', 'Mr. Robot', ['value' => 'mr_robot', 'selected' => true]); + $field->addChoice($option); + + $this->assertSame('mr_robot', $field->getValue(), '->addChoice() changes the value to added choice if selected attribute is set'); } public function testSelectWithEmptyBooleanAttribute()