Skip to content

Commit f22e612

Browse files
committed
Add dynamic help text generation for DurationType form
1 parent a77c9d3 commit f22e612

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

src/Form/DurationType.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,36 @@ public function configureOptions(OptionsResolver $resolver): void
166166

167167
return $data;
168168
});
169+
170+
$resolver->setNormalizer('help', function (Options $options, $value) {
171+
if (null === $value) {
172+
$dotFields = ['year', 'month', 'day'];
173+
$colonFields = ['hour', 'minute', 'second'];
174+
175+
$dotFields = array_values(array_filter($dotFields, static fn ($field) => isset($options[$field]) && $options[$field]));
176+
$colonFields = array_values(array_filter($colonFields, static fn ($field) => isset($options[$field]) && $options[$field]));
177+
178+
$value = '';
179+
180+
for ($index = 0, $lastIndex = \count($dotFields); $index < $lastIndex; ++$index) {
181+
if ($index === $lastIndex - 1 && 0 === \count($colonFields)) {
182+
$value .= \sprintf('%ss', $dotFields[$index]);
183+
} else {
184+
$value .= \sprintf('%ss.', $dotFields[$index]);
185+
}
186+
}
187+
188+
for ($index = 0, $lastIndex = \count($colonFields); $index < $lastIndex; ++$index) {
189+
if ($index === $lastIndex - 1) {
190+
$value .= \sprintf('%ss', $colonFields[$index]);
191+
} else {
192+
$value .= \sprintf('%ss:', $colonFields[$index]);
193+
}
194+
}
195+
}
196+
197+
return $value;
198+
});
169199
}
170200

171201
public function getBlockPrefix(): string

tests/Form/DurationTypeTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,11 @@ public function testConfigureAnotherUnit(): void
4343
]);
4444

4545
// Assert
46+
$view = $form->createView();
47+
4648
$this->assertTrue($form->isSynchronized());
4749
$this->assertEquals(new Second("5196852"), $form->getData()->getValue());
50+
$this->assertSame("months.hours:minutes:seconds", $view->vars['help']);
4851
}
4952

5053
public function testSubmitNull(): void
@@ -68,6 +71,7 @@ public function testWithPreData(): void
6871
// Act
6972
$view = $form->createView();
7073

74+
7175
// Assert
7276
$this->assertSame([
7377
'year' => null,
@@ -77,6 +81,8 @@ public function testWithPreData(): void
7781
'minute' => '12',
7882
'second' => null,
7983
], $view->vars['value']);
84+
85+
$this->assertSame("hours:minutes", $view->vars['help']);
8086
}
8187

8288
public function testWithNullPreData(): void
@@ -89,5 +95,6 @@ public function testWithNullPreData(): void
8995

9096
// Assert
9197
$this->assertNull($view->vars['value']);
98+
$this->assertSame("hours:minutes", $view->vars['help']);
9299
}
93100
}

0 commit comments

Comments
 (0)