Skip to content

Commit 41c6ab0

Browse files
committed
[Form] Field labels can now be passed in the 'label' option
1 parent 3d92549 commit 41c6ab0

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/Symfony/Component/Form/Type/FieldType.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ public function buildForm(FormBuilder $builder, array $options)
5656
->setAttribute('validation_groups', $options['validation_groups'])
5757
->setAttribute('error_mapping', $options['error_mapping'])
5858
->setAttribute('max_length', $options['max_length'])
59+
->setAttribute('label', $options['label'] ?: $this->humanize($builder->getName()))
5960
->setData($options['data'])
6061
->addValidator(new DefaultValidator())
6162
->addValidator(new DelegatingValidator($this->validator));
@@ -87,7 +88,7 @@ public function buildView(FormView $view, FormInterface $form)
8788
$view->setVar('class', null);
8889
$view->setVar('max_length', $form->getAttribute('max_length'));
8990
$view->setVar('size', null);
90-
$view->setVar('label', ucfirst(strtolower(str_replace('_', ' ', $form->getName()))));
91+
$view->setVar('label', $form->getAttribute('label'));
9192
$view->setVar('multipart', false);
9293
$view->setVar('attr', array());
9394

@@ -112,6 +113,7 @@ public function getDefaultOptions(array $options)
112113
'validation_groups' => null,
113114
'error_bubbling' => false,
114115
'error_mapping' => array(),
116+
'label' => null,
115117
);
116118

117119
if (!empty($options['data_class'])) {
@@ -140,4 +142,9 @@ public function getName()
140142
{
141143
return 'field';
142144
}
145+
146+
private function humanize($text)
147+
{
148+
return ucfirst(strtolower(str_replace('_', ' ', $text)));
149+
}
143150
}

tests/Symfony/Tests/Component/Form/AbstractLayoutTest.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,23 @@ public function testLabel()
133133
);
134134
}
135135

136-
public function testLabelWithCustomText()
136+
public function testLabelWithCustomTextPassedAsOption()
137+
{
138+
$form = $this->factory->create('text', 'na&me', array(
139+
'property_path' => 'name',
140+
'label' => 'Custom label',
141+
));
142+
$html = $this->renderLabel($form->createView());
143+
144+
$this->assertMatchesXpath($html,
145+
'/label
146+
[@for="na&me"]
147+
[.="[trans]Custom label[/trans]"]
148+
'
149+
);
150+
}
151+
152+
public function testLabelWithCustomTextPassedDirectly()
137153
{
138154
$form = $this->factory->create('text', 'na&me', array('property_path' => 'name'));
139155
$html = $this->renderLabel($form->createView(), 'Custom label');

0 commit comments

Comments
 (0)