diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php index 2e385a343f..e34c3e5bf4 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php @@ -329,7 +329,7 @@ class EntityChoiceList extends ObjectChoiceList protected function createIndex($entity) { if ($this->idAsIndex) { - return current($this->getIdentifierValues($entity)); + return $this->fixIndex(current($this->getIdentifierValues($entity))); } return parent::createIndex($entity); @@ -355,6 +355,23 @@ class EntityChoiceList extends ObjectChoiceList return parent::createValue($entity); } + /** + * {@inheritdoc} + */ + protected function fixIndex($index) + { + $index = parent::fixIndex($index); + + // If the ID is a single-field integer identifier, it is used as + // index. Replace any leading minus by underscore to make it a valid + // form name. + if ($this->idAsIndex && $index < 0) { + $index = strtr($index, '-', '_'); + } + + return $index; + } + /** * Loads the list with entities. */ diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/EntityChoiceListTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/EntityChoiceListTest.php index 3a2e9bba9f..e93ab1078d 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/EntityChoiceListTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/EntityChoiceListTest.php @@ -312,4 +312,47 @@ class EntityChoiceListTest extends DoctrineOrmTestCase $this->assertSame(array(0 => $entity1, 1 => $entity2), $choiceList->getChoices()); } + + public function testMinusReplacedByUnderscoreInNegativeIntIds() + { + $entity1 = new SingleIdentEntity(-1, 'Foo'); + $entity2 = new SingleIdentEntity(1, 'Bar'); + + // Persist for managed state + $this->em->persist($entity1); + $this->em->persist($entity2); + $this->em->flush(); + + $choiceList = new EntityChoiceList( + $this->em, + self::SINGLE_IDENT_CLASS, + 'name' + ); + + $this->assertSame(array('_1' => $entity1, 1 => $entity2), $choiceList->getChoices()); + $this->assertSame(array('_1', 1), $choiceList->getIndicesForChoices(array($entity1, $entity2))); + $this->assertSame(array('_1', 1), $choiceList->getIndicesForValues(array('-1', '1'))); + } + + public function testMinusReplacedByUnderscoreIfNotLoaded() + { + $entity1 = new SingleIdentEntity(-1, 'Foo'); + $entity2 = new SingleIdentEntity(1, 'Bar'); + + // Persist for managed state + $this->em->persist($entity1); + $this->em->persist($entity2); + $this->em->flush(); + + $choiceList = new EntityChoiceList( + $this->em, + self::SINGLE_IDENT_CLASS, + 'name' + ); + + // no getChoices()! + + $this->assertSame(array('_1', 1), $choiceList->getIndicesForChoices(array($entity1, $entity2))); + $this->assertSame(array('_1', 1), $choiceList->getIndicesForValues(array('-1', '1'))); + } }