diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php index 96f5e2f5f1868..37ef002a9526b 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php @@ -55,6 +55,26 @@ public function getEntities() */ public function getEntitiesByIds($identifier, array $values) { + if (null !== $this->queryBuilder->getMaxResults()) { + $metadata = $this->queryBuilder->getEntityManager()->getClassMetadata(current($this->queryBuilder->getRootEntities())); + + $choices = $unordered = []; + + foreach ($this->getEntities() as $entity) { + $id = current($metadata->getIdentifierValues($entity)); + if (false !== $i = array_search($id, $values, true)) { + $choices[$i] = $entity; + } + } + foreach ($values as $i => $value) { + if (isset($unordered[$i])) { + $choices[$i] = $unordered[$i]; + } + } + + return $choices; + } + $qb = clone $this->queryBuilder; $alias = current($qb->getRootAliases()); $parameter = 'ORMQueryBuilderLoader_getEntitiesByIds_'.$identifier; diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php index 147be98b90ce1..7edae7c260466 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php @@ -955,6 +955,32 @@ public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleIdentifie $this->assertNull($field->getData()); } + public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleIdentifierWithLimit() + { + $entity1 = new SingleIntIdEntity(1, 'Foo'); + $entity2 = new SingleIntIdEntity(2, 'Bar'); + $entity3 = new SingleIntIdEntity(3, 'Baz'); + + $this->persist([$entity1, $entity2, $entity3]); + + $repository = $this->em->getRepository(self::SINGLE_IDENT_CLASS); + + $field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [ + 'em' => 'default', + 'class' => self::SINGLE_IDENT_CLASS, + 'query_builder' => $repository->createQueryBuilder('e') + ->where('e.id IN (1, 2, 3)') + ->setMaxResults(1) + , + 'choice_label' => 'name', + ]); + + $field->submit('3'); + + $this->assertFalse($field->isSynchronized()); + $this->assertNull($field->getData()); + } + public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleAssocIdentifier() { $innerEntity1 = new SingleIntIdNoToStringEntity(1, 'InFoo'); @@ -1007,6 +1033,8 @@ public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureSingle $this->assertNull($field->getData()); } + + public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureCompositeIdentifier() { $entity1 = new CompositeIntIdEntity(10, 20, 'Foo');