[DomCrawler] Fixed the initial state for options without value attribute

This commit is contained in:
Christophe Coevoet 2014-05-17 12:49:12 +02:00
parent 0762bae059
commit 78cff96230
2 changed files with 11 additions and 6 deletions

View File

@ -232,22 +232,22 @@ class ChoiceFormField extends FormField
$found = false; $found = false;
foreach ($this->xpath->query('descendant::option', $this->node) as $option) { foreach ($this->xpath->query('descendant::option', $this->node) as $option) {
$this->options[] = $this->buildOptionValue($option); $optionValue = $this->buildOptionValue($option);
$this->options[] = $optionValue;
if ($option->getAttribute('selected')) { if ($option->getAttribute('selected')) {
$found = true; $found = true;
if ($this->multiple) { if ($this->multiple) {
$this->value[] = $option->getAttribute('value'); $this->value[] = $optionValue['value'];
} else { } else {
$this->value = $option->getAttribute('value'); $this->value = $optionValue['value'];
} }
} }
} }
// if no option is selected and if it is a simple select box, take the first option as the value // if no option is selected and if it is a simple select box, take the first option as the value
$option = $this->xpath->query('descendant::option', $this->node)->item(0); if (!$found && !$this->multiple && !empty($this->options)) {
if (!$found && !$this->multiple && $option instanceof \DOMElement) { $this->value = $this->options[0]['value'];
$this->value = $option->getAttribute('value');
} }
} }
} }

View File

@ -280,6 +280,11 @@ class ChoiceFormFieldTest extends FormFieldTestCase
{ {
$node = $this->createSelectNodeWithEmptyOption(array('foo' => false, 'bar' => false)); $node = $this->createSelectNodeWithEmptyOption(array('foo' => false, 'bar' => false));
$field = new ChoiceFormField($node); $field = new ChoiceFormField($node);
$this->assertEquals('foo', $field->getValue());
$node = $this->createSelectNodeWithEmptyOption(array('foo' => false, 'bar' => true));
$field = new ChoiceFormField($node);
$this->assertEquals('bar', $field->getValue());
$field->select('foo'); $field->select('foo');
$this->assertEquals('foo', $field->getValue(), '->select() changes the selected option'); $this->assertEquals('foo', $field->getValue(), '->select() changes the selected option');
} }