8000 [DomCrawler] Attach label to form fields · symfony/symfony@82ef55b · GitHub
[go: up one dir, main page]

Skip to content

Commit 82ef55b

Browse files
Carlos Ortega Huetosfabpot
Carlos Ortega Huetos
authored andcommitted
[DomCrawler] Attach label to form fields
1 parent 3c75c48 commit 82ef55b

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,30 @@ public function __construct(\DOMElement $node)
5757
$this->initialize();
5858
}
5959

60+
/**
61+
* Returns the label tag associated to the field or null if none.
62+
*
63+
* @return \DOMElement|null
64+
*/
65+
public function getLabel()
66+
{
67+
$xpath = new \DOMXPath($this->node->ownerDocument);
68+
69+
if ($this->node->hasAttribute('id')) {
70+
$labels = $xpath->query(sprintf('descendant::label[@for="%s"]', $this->node->getAttribute('id')));
71+
if ($labels->length > 0) {
72+
return $labels->item(0);
73+
}
74+
}
75+
76+
$labels = $xpath->query('ancestor::label[1]', $this->node);
77+
if ($labels->length > 0) {
78+
return $labels->item(0);
79+
}
80+
81+
return;
82+
}
83+
6084
/**
6185
* Returns the name of the field.
6286
*

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,38 @@ public function testGetSetHasValue()
3535

3636
$this->assertTrue($field->hasValue(), '->hasValue() always returns true');
3737
}
38+
39+
public function testLabelReturnsNullIfNoneIsDefined()
40+
{
41+
$dom = new \DOMDocument();
42+
$dom->loadHTML('<html><form><input type="text" id="foo" name="foo" value="foo" /><input type="submit" /></form></html>');
43+
44+
$field = new InputFormField($dom->getElementById('foo'));
45+
$this->assertNull($field->getLabel(), '->getLabel() returns null if no label is defined');
46+
}
47+
48+
public function testLabelIsAssignedByForAttribute()
49+
{
50+
$dom = new \DOMDocument();
51+
$dom->loadHTML('<html><form>
52+
<label for="foo">Foo label</label>
53+
<input type="text" id="foo" name="foo" value="foo" />
54+
<input type="submit" />
55+
</form></html>');
56+
57+
$field = new InputFormField($dom->getElementById('foo'));
58+
$this->assertEquals('Foo label', $field->getLabel()->textContent, '->getLabel() returns the associated label');
59+
}
60+
61+
public function testLabelIsAssignedByParentingRelation()
62+
{
63+
$dom = new \DOMDocument();
64+
$dom->loadHTML('<html><form>
65+
<label for="foo">Foo label<input type="text" id="foo" name="foo" value="foo" /></label>
66+
<input type="submit" />
67+
</form></html>');
68+
69+
$field = new InputFormField($dom->getElementById('foo'));
70+
$this->assertEquals('Foo label', $field->getLabel()->textContent, '->getLabel() returns the parent label');
71+
}
3872
}

0 commit comments

Comments
 (0)
0