Skip to content

Commit bcb03e0

Browse files
LuisDeimosfabpot
authored andcommitted
[Form] Fix Date\TimeType marked as invalid on request with single_text and zero seconds
1 parent 8d1711a commit bcb03e0

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Symfony/Component/Form/Extension/Core/Type/TimeType.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
namespace Symfony\Component\Form\Extension\Core\Type;
1313

1414
use Symfony\Component\Form\AbstractType;
15+
use Symfony\Component\Form\FormEvent;
16+
use Symfony\Component\Form\FormEvents;
1517
use Symfony\Component\Form\FormInterface;
1618
use Symfony\Component\Form\FormBuilderInterface;
1719
use Symfony\Component\Form\ReversedTransformer;
@@ -49,6 +51,17 @@ public function buildForm(FormBuilderInterface $builder, array $options)
4951

5052
if ('single_text' === $options['widget']) {
5153
$builder->addViewTransformer(new DateTimeToStringTransformer($options['model_timezone'], $options['view_timezone'], $format));
54+
55+
// handle seconds ignored by user's browser when with_seconds enabled
56+
// https://codereview.chromium.org/450533009/
57+
if ($options['with_seconds']) {
58+
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $e) {
59+
$data = $e->getData();
60+
if ($data && preg_match('/^\d{2}:\d{2}$/', $data)) {
61+
$e->setData($data.':00');
62+
}
63+
});
64+
}
5265
} else {
5366
$hourOptions = $minuteOptions = $secondOptions = array(
5467
'error_bubbling' => true,

src/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,22 @@ public function testSubmitStringSingleTextWithoutMinutes()
221221
$this->assertEquals('03', $form->getViewData());
222222
}
223223

224+
public function testSubmitWithSecondsAndBrowserOmissionSeconds()
225+
{
226+
$form = $this->factory->create('time', null, array(
227+
'model_timezone' => 'UTC',
228+
'view_timezone' => 'UTC',
229+
'input' => 'string',
230+
'widget' => 'single_text',
231+
'with_seconds' => true,
232+
));
233+
234+
$form->submit('03:04');
235+
236+
$this->assertEquals('03:04:00', $form->getData());
237+
$this->assertEquals('03:04:00', $form->getViewData());
238+
}
239+
224240
public function testSetDataWithoutMinutes()
225241
{
226242
$form = $this->factory->create('time', null, array(

0 commit comments

Comments
 (0)