8000 fix choice value for "false" in ChoiceType · symfony/symfony@5fd941e · GitHub
[go: up one dir, main page]

Skip to content

Commit 5fd941e

Browse files
committed
fix choice value for "false" in ChoiceType
1 parent b1e5149 commit 5fd941e

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/Symfony/Component/Form/ChoiceList/ArrayChoiceList.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ public function __construct($choices, $value = null)
7676

7777
if (null === $value && $this->castableToString($choices)) {
7878
$value = function ($choice) {
79-
return (string) $choice;
79+
return false === $choice ? '0' : (string) $choice;
8080
};
8181
}
8282

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,20 @@ public function testChoiceListAndChoicesCanBeEmpty()
126126
));
127127
}
128128

129+
public function testChoiceListWithBooleanAsValues()
130+
{
131+
$view = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(
132+
'choices' => array(
133+
'Yes' => true,
134+
'No' => false,
135+
),
136+
'choices_as_values' => true,
137+
))->createView();
138+
139+
$this->assertSame('1', $view->vars['choices'][0]->value);
140+
$this->assertSame('0', $view->vars['choices'][1]->value);
141+
}
142+
129143
public function testExpandedChoicesOptionsTurnIntoChildren()
130144
{
131145
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(
@@ -209,6 +223,30 @@ public function testPlaceholderNotPresentIfEmptyChoice()
209223
$this->assertCount(2, $form, 'Each choice should become a new field');
210224
}
211225

226+
public function testPlaceholderWithBooleanChoices()
227+
{
228+
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(
229+
'multiple' => false,
230+
'expanded' => true,
231+
'required' => false,
232+
'choices' => array(
233+
'Yes' => true,
234+
'No' => false,
235+
),
236+
'placeholder' => 'Select an option',
237+
'choices_as_values' => true,
238+
));
239+
240+
$this->assertTrue(isset($form['placeholder']), 'Placeholder should be set');
241+
$this->assertCount(3, $form, 'Each choice should become a new field, placeholder included');
242+
243+
$view = $form->createView();
244+
245+
$this->assertSame('Select an option', $view->vars['empty_value'], 'Placeholder should be selected');
246+
$this->assertSame('1', $view->vars['choices'][0]->value);
247+
$this->assertSame('0', $view->vars['choices'][1]->value, 'Choice "false" should have 0 as value');
248+
}
249+
212250
public function testExpandedChoicesOptionsAreFlattened()
213251
{
214252
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(

0 commit comments

Comments
 (0)
0