Skip to content

Commit a23a708

Browse files
committed
[DomCrawler] Allow to add choices to single select
1 parent 973495d commit a23a708

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

src/Symfony/Component/DomCrawler/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
7.1
5+
---
6+
7+
* Allow to add choices to single select
8+
49
7.0
510
---
611

src/Symfony/Component/DomCrawler/Field/ChoiceFormField.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,14 +143,14 @@ public function setValue(string|array|bool|null $value): void
143143
*/
144144
public function addChoice(\DOMElement $node): void
145145
{
146-
if (!$this->multiple && 'radio' !== $this->type) {
146+
if (!$this->multiple && ('radio' !== $this->type && 'select' !== $this->type)) {
147147
throw new \LogicException(sprintf('Unable to add a choice for "%s" as it is not multiple or is not a radio button.', $this->name));
148148
}
149149

150150
$option = $this->buildOptionValue($node);
151151
$this->options[] = $option;
152152

153-
if ($node->hasAttribute('checked')) {
153+
if ($node->hasAttribute('checked') || $node->hasAttribute('selected')) {
154154
$this->value = $option['value'];
155155
}
156156
}

src/Symfony/Component/DomCrawler/Tests/Field/ChoiceFormFieldTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,18 @@ public function testSelects()
110110
} catch (\InvalidArgumentException $e) {
111111
$this->assertTrue(true, '->setValue() throws an \InvalidArgumentException if the value is an array');
112112
}
113+
114+
$option = $this->createNode('option', 'Hello World', ['value' => 'hello_world']);
115+
$field->addChoice($option);
116+
117+
$this->assertNotSame('hello_world', $field->getValue());
118+
$field->setValue('hello_world');
119+
$this->assertSame('hello_world', $field->getValue(), '->setValue() changes the selected option to dynamically added one');
120+
121+
$option = $this->createNode('option', 'Mr. Robot', ['value' => 'mr_robot', 'selected' => true]);
122+
$field->addChoice($option);
123+
124+
$this->assertSame('mr_robot', $field->getValue(), '->addChoice() changes the value to added choice if selected attribute is set');
113125
}
114126

115127
public function testSelectWithEmptyBooleanAttribute()

0 commit comments

Comments
 (0)