diff --git a/src/Symfony/Component/DomCrawler/Field/FormField.php b/src/Symfony/Component/DomCrawler/Field/FormField.php index a6b33ded2d..1fa3e1de5f 100644 --- a/src/Symfony/Component/DomCrawler/Field/FormField.php +++ b/src/Symfony/Component/DomCrawler/Field/FormField.php @@ -57,6 +57,30 @@ abstract class FormField $this->initialize(); } + /** + * Returns the label tag associated to the field or null if none. + * + * @return \DOMElement|null + */ + public function getLabel() + { + $xpath = new \DOMXPath($this->node->ownerDocument); + + if ($this->node->hasAttribute('id')) { + $labels = $xpath->query(sprintf('descendant::label[@for="%s"]', $this->node->getAttribute('id'))); + if ($labels->length > 0) { + return $labels->item(0); + } + } + + $labels = $xpath->query('ancestor::label[1]', $this->node); + if ($labels->length > 0) { + return $labels->item(0); + } + + return; + } + /** * Returns the name of the field. * diff --git a/src/Symfony/Component/DomCrawler/Tests/Field/FormFieldTest.php b/src/Symfony/Component/DomCrawler/Tests/Field/FormFieldTest.php index 510f7628f2..d150eb3ac7 100644 --- a/src/Symfony/Component/DomCrawler/Tests/Field/FormFieldTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/Field/FormFieldTest.php @@ -35,4 +35,38 @@ class FormFieldTest extends FormFieldTestCase $this->assertTrue($field->hasValue(), '->hasValue() always returns true'); } + + public function testLabelReturnsNullIfNoneIsDefined() + { + $dom = new \DOMDocument(); + $dom->loadHTML('
'); + + $field = new InputFormField($dom->getElementById('foo')); + $this->assertNull($field->getLabel(), '->getLabel() returns null if no label is defined'); + } + + public function testLabelIsAssignedByForAttribute() + { + $dom = new \DOMDocument(); + $dom->loadHTML(''); + + $field = new InputFormField($dom->getElementById('foo')); + $this->assertEquals('Foo label', $field->getLabel()->textContent, '->getLabel() returns the associated label'); + } + + public function testLabelIsAssignedByParentingRelation() + { + $dom = new \DOMDocument(); + $dom->loadHTML(''); + + $field = new InputFormField($dom->getElementById('foo')); + $this->assertEquals('Foo label', $field->getLabel()->textContent, '->getLabel() returns the parent label'); + } }