take into account all label related options

This commit is contained in:
Christian Flothmann 2021-01-27 21:50:32 +01:00
parent bdf3589918
commit adb0fd1c7d
2 changed files with 28 additions and 1 deletions

View File

@ -113,8 +113,18 @@ final class FormExtension extends AbstractExtension
public function getFieldLabel(FormView $view): ?string
{
if (false === $label = $view->vars['label']) {
return null;
}
if (!$label && $labelFormat = $view->vars['label_format']) {
$label = str_replace(['%id%', '%name%'], [$view->vars['id'], $view->vars['name']], $labelFormat);
} elseif (!$label) {
$label = ucfirst(strtolower(trim(preg_replace(['/([A-Z])/', '/[_\s]+/'], ['_$1', ' '], $view->vars['name']))));
}
return $this->createFieldTranslation(
$view->vars['label'],
$label,
$view->vars['label_translation_parameters'] ?: [],
$view->vars['translation_domain']
);

View File

@ -81,6 +81,7 @@ class FormExtensionFieldHelpersTest extends FormIntegrationTestCase
],
],
'choice_translation_domain' => 'forms',
'label_format' => 'label format for field "%name%" with id "%id%"',
])
->add('choice_multiple', ChoiceType::class, [
'choices' => [
@ -89,6 +90,7 @@ class FormExtensionFieldHelpersTest extends FormIntegrationTestCase
],
'multiple' => true,
'expanded' => true,
'label' => false,
])
->getForm()
;
@ -121,6 +123,21 @@ class FormExtensionFieldHelpersTest extends FormIntegrationTestCase
$this->assertSame('[trans]base.username[/trans]', $this->translatorExtension->getFieldLabel($this->view->children['username']));
}
public function testFieldLabelFromFormat()
{
$this->assertSame('label format for field "choice_grouped" with id "register_choice_grouped"', $this->rawExtension->getFieldLabel($this->view->children['choice_grouped']));
}
public function testFieldLabelFallsBackToName()
{
$this->assertSame('Choice flat', $this->rawExtension->getFieldLabel($this->view->children['choice_flat']));
}
public function testFieldLabelReturnsNullWhenLabelIsDisabled()
{
$this->assertNull($this->rawExtension->getFieldLabel($this->view->children['choice_multiple']));
}
public function testFieldHelp()
{
$this->assertSame('base.username_help', $this->rawExtension->getFieldHelp($this->view->children['username']));